ADO.Net C#与SQL Server数据库连接

时间:2022-01-04 04:05:45

第一步配置AppConfig

2008版本SQLServer数据库

<connectionStrings>
<add name="connstr" connectionString="Data Source=.;Initial Catalog=RuanmouVipHomework ;User Id=sa;Password=sa;"></add>
</connectionStrings>

Data Source:服务器地址,本地为(Local)或 点.。

Initial Catalog:数据库名称

User Id,Password:数据库用户名,用户密码

一,多行查询

public static readonly string connstr =ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;  //获取数据库信息
public static void getConnection(){
using (SqlConnection connection = new SqlConnection(connstr))  //SqlConnection为建立和数据库连接的对象
{
connection.Open();          //开启连接
SqlCommand command = connection.CreateCommand(); //建立接收命令的对象
command.CommandText = "select * from Company";        //对象赋值,填充sql语句及命令
using(SqlDataReader reader=command.ExecuteReader())  //建立读取数据的对象
{
while(reader.Read())           //读取数据
{
string name=reader.GetString(1);//获得第1列的值
DateTime creattime = reader.GetDateTime(2); //获得第2列列的值
int creatorid = reader.GetInt32(3);//获得第3列列的值
int lastmodifierid = reader.GetInt32(4); //获得第4列列的值
DateTime lastmodifytime = reader.GetDateTime(5); //获得第5列列的值
Console.WriteLine(name);
Console.WriteLine(creattime.ToString());
Console.WriteLine(creatorid.ToString());
Console.WriteLine(lastmodifytime.ToString());
}
}
}
}

 

二,添加,修改,删除

1添加如下,修改,删除只要更换sql语句就行

public static void InsertData()
{
using (SqlConnection connection = new SqlConnection(connstr))
{
connection.Open();
// Do work here; connection closed on following line.
SqlCommand command = connection.CreateCommand(); 
command.CommandText = "insert into Company (Name,CreateTime,CreatorId) VALUES ('王红','2017/01/12',1) ";
var adata = command.ExecuteNonQuery();
Console.WriteLine(adata);
}
}