简体   繁体   English

如何在 C# 中使用 ADO.NET 执行 SQL 命令?

[英]How to execute SQL command using ADO.NET in C#?

First of all, I passed the connection string to SqlConnection as parameter:首先,我将连接字符串作为参数传递给SqlConnection

SqlConnection con = new SqlConnection("server=ZIKO_RED2486;database=Students;Integrated Security = true"); 

Then I open that connection:然后我打开那个连接:

con.Open();

and I also created the query string:我还创建了查询字符串:

string query = "INSERT INTO Students VALUES ('"+txt_id.Text+"','"+txt_fname.Text+"','"+txt_sname.Text+"','"+txt_numberP+"','"+txt_age.Text +"')";

Then I passed it as parameter with the connection inside SqlCommand + execute it + close the connection:然后我将它作为参数传递给SqlCommand中的连接+执行它+关闭连接:

    SqlCommand cmd = new SqlCommand(query, con);
    cmd.ExecuteNonQuery();
    con.Close();

But when I run the app, I get an exception:但是当我运行应用程序时,我得到一个异常:

System.Data.SqlClient.SqlException: 'Invalid object name' System.Data.SqlClient.SqlException:'无效的 object 名称'

I created the table Students with five columns ( id, f_name, s_name, number_p, age ) before all of that.在此之前,我创建了包含五列( id, f_name, s_name, number_p, age )的Students表。

Thanks for your help in advance提前感谢您的帮助

string query = "INSERT INTO Students VALUES
 ("+txt_id.Text+",'"+txt_fname.Text+"','"+txt_sname.Text+"','"+txt_numberP.Text+"','"+txt_age.Text +"')";

try this query !试试这个查询!

I think you declare id as int primary key so we don't put id between quotes ' '我认为您将 id 声明为int主键,因此我们不会将 id 放在引号' '之间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM