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

本文关键字:SQL Server 数据库 插入 datatable 数据 | 更新日期: 2023-09-27 18:17:08

我几乎尝试了这个网站上的所有解决方案,但我无法解决这个问题。我有通过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)

就像我说的没有错误出现。数据只是没有保存到数据库

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

"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,因为它是money。

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

|DataDirectory|设置应用程序所在文件夹的路径。在这种情况下,如果我们在Debug模式下运行,它将在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";