我从 Excel 电子表格中选择 *
到 DataTable
dt
中。我想获取这些值并更新 SQL 表。 SQL 表存在是因为从原始 Excel 电子表格手动导入到 SQL,具有主键集。用户更新了 Excel 工作表,我需要更新 SQL 值。我正在将 dt.RowState
设置为 modified 以调用更新。我没有收到任何错误,但 SQL 表没有更新。之前的测试显示我的 SQL 权限和连接良好,我可以修改表。
connectionToSQL = new SqlConnection(SQLConnString);
connectionToSQL.Open();
var cmd = new SqlCommand("SELECT * FROM TAGS$",connectionToSQL);
var da = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da);
foreach (DataRow r in dt.Rows)
{
r.SetModified();
}
da.Update(dt);
试试这个:
using System.Data;
using System.Data.SqlClient;
using System;
namespace Q308507 {
class Class1
{
static void Main(string[] args)
{
SqlConnection cn = new SqlConnection();
DataSet CustomersDataSet = new DataSet();
SqlDataAdapter da;
SqlCommandBuilder cmdBuilder;
// Set the connection string of the SqlConnection object
// to connect to the SQL Server database in which you
// created the sample table.
cn.ConnectionString =
"Server=server;Database=northwind;UID=login;PWD=password;";
cn.Open();
// Initialize the SqlDataAdapter object by specifying a
// Select command that retrieves data from the sample table.
da = new SqlDataAdapter("select * from CustTest order by CustId", cn);
// Initialize the SqlCommandBuilder object to automatically
// generate and initialize the UpdateCommand,
// InsertCommand, and DeleteCommand properties
// of the SqlDataAdapter.
cmdBuilder = new SqlCommandBuilder(da);
// Populate the DataSet by running the Fill method
// of the SqlDataAdapter.
da.Fill(CustomersDataSet, "Customers");
// Display the Update, Insert, and Delete commands
// that were automatically generated
// by the SqlCommandBuilder object.
Console.WriteLine(
"Update command Generated by the Command Builder : ");
Console.WriteLine(
"==================================================");
Console.WriteLine(
cmdBuilder.GetUpdateCommand().CommandText);
Console.WriteLine(" ");
Console.WriteLine(
"Insert command Generated by the Command Builder : ");
Console.WriteLine(
"==================================================");
Console.WriteLine(cmdBuilder.GetInsertCommand().CommandText);
Console.WriteLine(" ");
Console.WriteLine(
"Delete command Generated by the Command Builder : ");
Console.WriteLine(
"==================================================");
Console.WriteLine(cmdBuilder.GetDeleteCommand().CommandText);
Console.WriteLine(" ");
// Write out the value in the CustName field before
// updating the data using the DataSet.
Console.WriteLine("Customer Name before Update : " +
CustomersDataSet.Tables["Customers"].Rows[0]["CustName"]);
// Modify the value of the CustName field.
CustomersDataSet.Tables["Customers"].Rows[0]["CustName"] = "Jack";
// Post the data modification to the database.
da.Update(CustomersDataSet, "Customers");
Console.WriteLine("Customer Name updated successfully");
// Close the database connection.
cn.Close();
// Pause
Console.ReadLine();
}
}
}