我需要写一个程序.程序的一部分是写入sql数据库(.mdf).我在尝试向表中添加新行时遇到了很多麻烦(称为“数据”).这是代码:...DataSet ds = new DataSet();System.Data.SqlClient.SqlDataAdapter da;DataRow dRow;...

我需要写一个程序.程序的一部分是写入sql数据库(.mdf).
我在尝试向表中添加新行时遇到了很多麻烦(称为“数据”).这是代码:
...
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da;
DataRow dRow;
string sql = "SELECT * From Data";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
...
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
dRow = ds.Tables["Data"].NewRow();
dRow[0] = "my_data1";
dRow[1] = "my_data2";
dRow[2] = "my_data3";
...
ds.Tables["Data"].Rows.Add(dRow);
da.Update(ds, "Data");
...
我执行此代码,但数据没有保存到表中.有谁知道如何在表中输入新行并保存它?
解决方法:
您的SqlDataAdapter中需要一个InsertCommand.
编辑:
这是我掀起的一个简单例子.还有很多其他的,但这应该让你去.它假设您有一个包含两列的表(dbo.Foos)(Foo int,Bar nvarchar(50)).
namespace DataAdapterSample
{
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
using (SqlConnection connection = new SqlConnection(@"Data Source=[your server];Initial Catalog=[your database];Integrated Security=true;"))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter())
{
dataAdapter.SelectCommand = new SqlCommand("select Foo, Bar from dbo.Foos", connection);
dataAdapter.InsertCommand = new SqlCommand("insert into dbo.Foos (Foo, Bar) values (@Foo, @Bar)", connection);
dataAdapter.InsertCommand.Parameters.Add(new SqlParameter("Foo", SqlDbType.Int, 4, "Foo"));
dataAdapter.InsertCommand.Parameters.Add(new SqlParameter("Bar", SqlDbType.NText, 50, "Bar"));
using (DataSet dataSet = new DataSet())
{
dataAdapter.Fill(dataSet);
Console.WriteLine("There are {0} rows in the table", dataSet.Tables[0].Rows.Count);
DataRow newRow = dataSet.Tables[0].NewRow();
newRow["Foo"] = 5;
newRow["Bar"] = "Hello World!";
dataSet.Tables[0].Rows.Add(newRow);
dataAdapter.Update(dataSet);
}
//Just to prove we inserted
using (DataSet newDataSet = new DataSet())
{
dataAdapter.Fill(newDataSet);
Console.WriteLine("There are {0} rows in the table", newDataSet.Tables[0].Rows.Count);
}
}
}
Console.ReadLine();
}
}
}
织梦狗教程
本文标题为:如何使用c#sql server向现有表添加新行


基础教程推荐
猜你喜欢
- c# – 是否可以在远程Windows机器上创建性能计数器? 2023-09-19
- C#的通用DbHelper类(支持数据连接池)示例详解 2023-05-26
- Unity使用EzySlice实现模型多边形顺序切割 2023-03-03
- C# 获取指定QQ头像绘制圆形头像框GDI(Graphics)的方法 2023-05-06
- C# 程序通用结构 2023-05-11
- Unity实现UI渐变效果 2023-02-15
- C#用Topshelf创建Windows服务的步骤分享 2023-02-16
- C#使用Dictionary<string, string>拆分字符串与记录log方法 2023-06-04
- 基于Kubernetes实现前后端应用的金丝雀发布(两种方案) 2023-05-10
- c#之mysql三种带事务批量插入 2023-11-11