c# - 如何在 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
) 的表。
提前感谢您的帮助
解决方案
string query = "INSERT INTO Students VALUES
("+txt_id.Text+",'"+txt_fname.Text+"','"+txt_sname.Text+"','"+txt_numberP.Text+"','"+txt_age.Text +"')";
试试这个查询!
我认为您将 id 声明int
为主键,因此我们不会将 id 放在引号之间' '
推荐阅读
- html - 响应式 div 元素与背景图像相同?
- python - Tensorflow 2 ValueError:没有为任何变量提供梯度:自定义损失函数
- sql - Clickhouse 数组字段 - 检查是否有任何项目符合条件
- javascript - array.map() 不会在 React 的网格容器中水平渲染项目
- react-native - React Native Facebook Flipper 线程 9:EXC_BAD_ACCESS(代码=1,地址=0x20...1)
- elasticsearch - 映射时出现 Elasticsearch 错误 - 未知设置
- c++ - 我可以在 C++ 中使用数组作为 struct 的属性吗?
- python - 如何从 keras 中的单个自定义损失函数访问所有输出
- reactjs - reactjs:如何根据后端权限显示导航项目
- java - 根据正则表达式拆分数组