【发布时间】:2014-08-27 05:24:38
【问题描述】:
我在将数据网格更改写入数据库时遇到问题,我尝试在网格上输入更改,然后当按下 Button_Add_Car 时,我执行此代码并将更改写入数据库,但没有任何内容写入数据库.
private void Button_Add_Car(object sender, RoutedEventArgs e)
{
SqlConnection cn = new SqlConnection();
DataSet dt = new DataSet();
SqlDataAdapter da;
SqlCommandBuilder cmdBuilder;
cn.ConnectionString = (String.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
cn.Open();
da = new SqlDataAdapter("SELECT * FROM Cars", cn);
cmdBuilder = new SqlCommandBuilder(da);
da.Fill(dt);
da.Update(dt);
cn.Close();
}
- 我使用这种方法是否走在正确的轨道上?
- 我是否使用了正确的 SQL 查询?我对 SELECT/INSERT 感到困惑,因为我发现了人们同时使用这两种方法来实现我想要做的事情的例子。当然我应该使用 INSERT 语句。
我制作了自己的自定义 SQL 命令来手动插入数据库,因此它实际上可以工作:
SQLCmd("INSERT INTO Cars (Date, Time) VALUES(2014-10-10, '12:00:00')");
编辑 1:
感谢 marc_s,我设法实现了某种插入,但我相信我需要将 value 部分修改为在 IF 语句中,该语句将检查它是否为 null 并将 value 更改回 cr.Date 和 cr .Time 我正在使用一个列表。我不确定如何以这种方式使用 if 语句,因为它当前正在输入空白行,尽管它是朝着正确方向迈出的一步:
CarRecord cr = new CarRecord();
carRecords.Add(cr);
SqlConnection con = new SqlConnection(String.Format(@"Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}", SQLFunctions.connectSQL.SQLSERVER_ID, SQLFunctions.connectSQL.SQLDatabaseName, SQLFunctions.connectSQL.SQLServerLoginName, SQLFunctions.connectSQL.SQLServerPassword));
con.Open();
SqlCommand comm = new SqlCommand("INSERT INTO Cars VALUES (@Date, @Time)", con);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.SelectCommand.Parameters.Add(new SqlParameter("@Date", SqlDbType.NVarChar)).Value = DBNull.Value;
da.SelectCommand.Parameters.Add(new SqlParameter("@Time", SqlDbType.NVarChar)).Value = DBNull.Value;
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Update(dt);
con.Close();
【问题讨论】:
-
一句忠告:不要将您的 SQL 语句作为字符串连接在一起。这会导致 SQL 注入漏洞,也会导致性能下降。改用参数化查询,这样更快且不受 SQL 注入的影响!
-
使用ADO.Net插入:stackoverflow.com/questions/14090914/…
-
用当前进度编辑问题。
标签: c# sql-server datagrid