如何在C#中更新SQL数据库表 [英] How can I update SQL database table in C#

查看:449
本文介绍了如何在C#中更新SQL数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行我的程序时,它会显示以下错误消息:



对于不返回任何键列的SelectCommand,不支持更新命令的动态SQL生成信息。'





好​​吧,我试图更改代码,所以如果我改为:



dt.AcceptChanges();

da.Update(dt);



它没有显示错误消息,但更改没有进入数据库。

请帮助我。



我尝试过:



使用(SqlConnection dbcon = new SqlConnection(clsmain.connection_str))

{

string querystring = select * from tblmain where ticker ='+ ticker_str +';

using(SqlDataAdapter da = new SqlDataAdapter())

{

da.SelectCommand = new SqlCommand(querystring,dbcon);

SqlCommandBuilder objCommandBuilder = new SqlCommandB uilder(da);

使用(DataTable dt = new DataTable())

{

if(dbcon.State == ConnectionState.Closed )dbcon.Open();

int countofrecords = da.Fill(dt);



。 //我的变更数据代码在这里

。 //例如::

。 // dt.Rows [i] [avgloss] = 10.22;



if(dbcon.State == ConnectionState.Closed){dbcon.Open() ; }

da.Update(dt);

}

}

}

When I run my program it shows bellow error message :

Dynamic SQL generation for the Update Command is not supported against a SelectCommand that does not return any key column information.'


well , I tried to change code so if I change to this:

dt.AcceptChanges();
da.Update(dt);

it doesn't show error message but changes had no taken to the database.
Please help me.

What I have tried:

using (SqlConnection dbcon = new SqlConnection(clsmain.connection_str))
{
string querystring = "select * from tblmain where ticker='" + ticker_str + "'";
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = new SqlCommand(querystring, dbcon);
SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(da);
using (DataTable dt = new DataTable())
{
if (dbcon.State == ConnectionState.Closed) dbcon.Open();
int countofrecords = da.Fill(dt);
.
. // my code for change data is here
. // for example::
. // dt.Rows[i]["avgloss"]=10.22;
.
if (dbcon.State == ConnectionState.Closed) { dbcon.Open(); }
da.Update(dt);
}
}
}

推荐答案

你正在使用SelectCommand的SELECT *。不要这样做。拼出你想要的每一列,确保你还返回执行SELECT的表的主键列。



没有列出的列和主键在该列表中的列中,SqlCommandBuilder无法为这些操作构建INSERT,UPDATE和DELETE SQL语句。
You're using a "SELECT *" om your SelectCommand. DO NOT DO THIS. Spell out each column you want, making sure you also return the primary key column of the table your executing the SELECT on.

Without the columns spelled out and the primary key column in that list, the SqlCommandBuilder cannot build the INSERT, UPDATE, and DELETE SQL statements for these operations.


这篇关于如何在C#中更新SQL数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆