C#将数据从datatable插入到SQL Server数据库

时间:2016-11-10 04:48:56

标签: c# sql-server database datatable

我已尝试过本网站上的几乎所有解决方案,但我无法解决这个问题。我有通过ODBC连接从数据库检索的数据。数据就在那里。它会很好地进入数据网格视图,但我无法将这些数据导入我的本地SQL数据库。请告诉我我做错了什么。

    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)

就像我说的,没有错误出现。数据不会保存到数据库中。

2 个答案:

答案 0 :(得分:1)

"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() + ");";

删除FNCL_SPLIT_REC_ID之间的'',因为它是int和SALES_SRC_PRC,因为它是钱。

答案 1 :(得分:0)

我发现您实施的代码没有错误。我发现mdf文件的连接定义是错误的。

|DataDirectory|设置应用程序运行的文件夹的路径。在这种情况下,如果我们在调试模式下运行,它将在Debug \ bin文件夹中创建单独的应用程序exe,其中包含.mdf文件等应用程序资源。或者在发布模式下,它将在发布文件夹中创建特定文件夹。因此,您需要更改数据库连接的数据库文件名,或者需要为连接字符串提供整个目录路径。实施例

tempDbConnection.ConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\TempDB.mdf;Integrated Security=True";
}

替换

tempDbConnection.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Promod\Documents\Visual Studio 2012\Projects\Contribution1\Contribution1\bin\Debug\TempDB.mdf;Integrated Security=True";
相关问题