Insert into C# with SQLCommand(使用 SQLCommand 插入 C#)
问题描述
将数据插入数据库的最佳方法是什么?
What's the best way to INSERT data into a database?
这是我所拥有的,但它是错误的..
This is what I have but it's wrong..
cmd.CommandText = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
cmd.Parameters.Add(new SqlParameter("@param1", klantId));
cmd.Parameters.Add(new SqlParameter("@param2", klantNaam));
cmd.Parameters.Add(new SqlParameter("@param3", klantVoornaam));
函数将数据添加到列表框
The function add data into the listBox
http://www.pictourl.com/viewer/37e4edcf (链接失效)
但没有进入数据库..
http://www.pictourl.com/viewer/4d5721fc (链接失效)
完整功能:
private void Form1_Load(object sender, EventArgs e)
{
conn2 = new SqlConnection();
conn2.ConnectionString = ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString;
}
private void button2_Click(object sender, EventArgs e)
{
string sqlCmd = "SELECT naam,voornaam,klant_id FROM klant;";
SqlCommand cmd = new SqlCommand(sqlCmd, conn2);
conn2.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox2.Items.Add(reader.GetString(0) + " " + reader.GetString(1) + " (" + reader.GetInt16(2) + ")");
}
}
conn2.Close();
}
private void button4_Click(object sender, EventArgs e)
{
int klantId = Convert.ToInt32(textBox1.Text);
string klantNaam = textBox2.Text;
string klantVoornaam = textBox3.Text;
conn2.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn2;
cmd.CommandText = "INSERT INTO klant(klant_id, naam, voornaam) VALUES(@param1,@param2,@param3)";
cmd.Parameters.AddWithValue("@param1", klantId);
cmd.Parameters.AddWithValue("@param2", klantNaam);
cmd.Parameters.AddWithValue("@param3", klantVoornaam);
cmd.ExecuteNonQuery();
conn2.Close();
}
推荐答案
尝试确认数据库中每个参数的数据类型(SqlDbType),这样做;
Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
using(SqlCommand cmd = new SqlCommand(sql,connection))
{
cmd.Parameters.Add("@param1", SqlDbType.Int).Value = klantId;
cmd.Parameters.Add("@param2", SqlDbType.VarChar, 50).Value = klantNaam;
cmd.Parameters.Add("@param3", SqlDbType.VarChar, 50).Value = klantVoornaam;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
这篇关于使用 SQLCommand 插入 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 SQLCommand 插入 C#


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01