//引用系统命名空间
using System;
using System.Data;using System.Data.SqlClient;
//项目生成的命名空间
namespace ConsoleApplication3
{
//项目中的类
class Program
{
//项目执行入口
static void Main()
{适配器字符串是什么
String connectionString = GetConnectionString();
//定义数据库连接对象
SqlConnection connection = new SqlConnection(connectionString);
//定义SQL字符串
String MySQL = "Select * From T_STUDENT;";
//定义数据适配器对象
SqlDataAdapter MyAdapter = new SqlDataAdapter(MySQL, connection);
{
try
{
/
/打开数据库连接
connection.Open();
MyAdapter.SelectCommand=new SqlCommand(MySQL, connection);
//定义数据集对象
DataSet MyDataSet = new DataSet();
//填充数据集的数据
MyAdapter.Fill(MyDataSet, "T_STUDENT");
//定义数据表对象
DataTable MyTable=MyDataSet.Tables["T_STUDENT"];
//定义一个全新的数据行对象
DataRow MyRow =MyTable.NewRow();
/
/定义数据行中各字段的值
MyRow["T_S_NAME"]="陈超";
MyRow["T_S_SEX"]="男";
MyRow["T_S_BIRTHDAY"]="1985-09-11";
MyRow["T_S_ID"]=2002080524;
MyRow["T_S_NATIONALITY"]="汉";
MyRow["T_S_PHOTO"]=null;
//在内存中的表对象中添加一个新行,但此时新行的内容没有更新到数据源中
MyTable.Rows.Add(MyRow);
//定义数据适配器对象的InsertCommand属性的Insert语句
MyAdapter.InsertCommand = new SqlCommand("Insert Into T_STUDENT(T_S_NAME,T_S_SEX,T_S
_BIRTHDAY," +"T_S_ID,T_S_NATIONALITY,T_S_PHOTO) Values('"+MyRow["T_S_NAME"]+"','"+MyRow ["T_S_SEX"]+"','"+MyRow["T_S_BIRTHDAY"]+"',"+MyRow["T_S_ID"]+",'"+MyRow ["T_S_NATIONALITY"]+"',"+MyRow["T_S_PHOTO"]+" null)",connection);
//显示Insert语句是否正常
Console.WriteLine(MyAdapter.InsertCommand.CommandText.ToString());
//调用数据适配器的Update方法,将新插入的数据更新到数据源中
MyAdapter.Update(MyDataSet, "T_STUDENT");
Console.WriteLine("成功更新数据库的数据!");
}catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
finally
{
connection.Close();
Console.ReadLine();
Console.WriteLine("成功关闭到SQL Server 2005数据库的连接");
}
}
}
//返回连接字符串的函数
static private string GetConnectionString()
{
return "Integrated Security=Yes;
Initial Catalog=DB_student;
Server=Mynetserver";
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论