ASP.NET(C#)连接数据库和操作数据库

首先加入命名空间using System.Data;using System.Data.SqlClient;

1.查询

SqlConnection conn = new SqlConnection(); 

conn = new SqlConnection(); 

conn.ConnectionString = "Data Source=(local);Initial Catalog=数据库名;UserID=sa;Password=123456"; 

conn.Open(); 

string strsql=“select语句"; 

SqlCommand cmd = new SqlCommand(strsql, conn); 

SqlDataReader sqlreader = cmd.ExecuteReader(); 

while (sqlreader.Read()) 

{

       txtName.Text= sqlreader["列名"].ToString();

 } 

sqlreader.Close();

 conn.Close();

2.插入、更新、删除

 SqlConnection conn = new SqlConnection(); 

conn = new SqlConnection(); 

conn.ConnectionString = "Data Source=(local);Initial Catalog=数据库名;UserID=sa;Password=123456";

 conn.Open(); 

strsql="update语句";

// strsql="插入语句";

//strsql="删除语句"; 

SqlCommand sqlcmd2 = new SqlCommand(strsql, conn);

 int iResult = sqlcmd2.ExecuteNonQuery(); 

conn.Close();

 

posted @ 2013-12-17 23:16  Little_C  阅读(686)  评论(0编辑  收藏  举报