首页 > 解决方案 > 如何在 C# 中使用 ADO.NET 执行 SQL 命令?

问题描述

首先,我将连接字符串SqlConnection作为参数传递给:

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

然后我打开那个连接:

con.Open();

我还创建了查​​询字符串:

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

然后我将它作为参数传递给里面的连接SqlCommand+执行它+关闭连接:

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

但是当我运行应用程序时,我得到一个异常:

System.Data.SqlClient.SqlException:'无效的对象名称'

在所有这些之前,我创建了Students包含五列 ( id, f_name, s_name, number_p, age) 的表。

提前感谢您的帮助

标签: c#sql-serverado.netsqlcommand

解决方案


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

试试这个查询!

我认为您将 id 声明int为主键,因此我们不会将 id 放在引号之间' '


推荐阅读