我已經嘗試過幾乎所有的解決方案,但我無法解決這個問題。我有通過ODBC連接從數據庫中檢索的數據。數據在那裏。它將進入數據網格視圖,但我無法獲取這些數據進入我的本地SQL數據庫。請告訴我我做錯了什麼。C#從數據表插入數據到SQL Server數據庫
public partial class frmNorth : Form
{
// variables for the connections
private OdbcConnection epnConnection = new OdbcConnection();
private SqlConnection tempDbConnection = new SqlConnection();
public frmNorth()
{
InitializeComponent();
// This is for the ePN DB
epnConnection.ConnectionString = @"Dsn=ePN; uid=username; pwd=myPa$$Word";
// This is for the local DB
tempDbConnection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TempDB.mdf;Integrated Security=True";
}
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
//===This part works just fine===============================================================
epnConnection.Open();
string epnQuery = "SELECT FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC " +
"FROM PROJ_FNCL_SPLIT " +
"WHERE PROJ_ID=" + textBox1.Text + "";
OdbcCommand epnCommand = new OdbcCommand(epnQuery, epnConnection);
epnCommand.CommandTimeout = 0;
//This connects the data to the data table
OdbcDataAdapter da = new OdbcDataAdapter(epnCommand);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
//===========================================================================================
//======The part below is the part that wont work. The data wont go into the SQL database====
tempDbConnection.Open();
string tempSql = "";
for (int i = 0; i < dt.Rows.Count; i++)
{
tempSql = "INSERT INTO tblTemp (FNCL_SPLIT_REC_ID, PROJ_ID, SALES_SRC_PRC) VALUES ('"
+ dt.Rows[i]["FNCL_SPLIT_REC_ID"].ToString().Trim() + "','"
+ dt.Rows[i]["PROJ_ID"].ToString().Trim() + "','"
+ dt.Rows[i]["SALES_SRC_PRC"].ToString().Trim() + "');";
SqlCommand tempCommand = new SqlCommand(tempSql, tempDbConnection);
tempCommand.ExecuteNonQuery();
}
// There are no errors. The data just doesn't save to the database.
//===========================================================================================
epnConnection.Close();
tempDbConnection.Close();
}
catch (Exception ex)
{
epnConnection.Close();
tempDbConnection.Close();
MessageBox.Show("Error " + ex);
}
}
}
}
//+++++++++++++++++++This is what the table looks like+++++++++++++++++++++++++++++++++++++++++++++++
CREATE TABLE [dbo].[tblTemp] (
[FNCL_SPLIT_REC_ID] INT NOT NULL,
[PROJ_ID] NCHAR (10) NULL,
[SALES_SRC_PRC] MONEY NULL,
PRIMARY KEY CLUSTERED ([FNCL_SPLIT_REC_ID] ASC)
就像我說的沒有錯誤出現。數據只是不保存到數據庫。
您需要通過線通過您的代碼行的方式執行,並觀察其運行。然後您需要使用SQL Profiler來觀察正在執行的查詢 –
由於您沒有得到錯誤和驗證執行!你正在檢查正確的數據庫和表插入? – Adil