码迷,mamicode.com
首页 > 数据库 > 详细

C#中连接数据库及操作的例子(转)

时间:2015-09-07 12:55:12      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

using System.Data;
using System.Data.SqlClient;


SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=stu;uid=sa;pwd=sa";
con.Open();

/*
SqlDataAdapter 对象。 用于填充DataSet (数据集)。
SqlDataReader 对象。 从数据库中读取流..
后面要做增删改查还需要用到 DataSet 对象。
*/


//新增、修改、删除
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText = "update users set name=@name,pwd=@pwd where id=@id";

SqlParameter parn = new SqlParameter("@name", name); 
cmd.Parameters.Add(parn); 
SqlParameter parp = new SqlParameter("@pwd", pwd);             cmd.Parameters.Add(parp);
SqlParameter pari = new SqlParameter("@id", id);             cmd.Parameters.Add(pari);

cmd.ExecuteNonQuery()

conn.Close();            
cmd.Dispose();

//若是执行存储过程(例)
 cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.VarChar, 64).Value = orderid;
cmd.Parameters.Add("@PrintNo", SqlDbType.Int, 32).Value = mPrintNo;
cmd.CommandText = "UpdateSalePrintNo";
cmd.ExecuteNonQuery();

//查询
string sql = "select * from users";
SqlCommand cmd = new SqlCommand(sql, conn);
//或 
SqlCommand cmd = new SqlCommand()
cmd.Connection =con;
cmd.CommandText = sql ;
SqlDataAdapter da = new SqlDataAdapter(cmd);            
DataTable dt = new DataTable();             
da.Fill(dt);                       

conn.Close();             
cmd.Dispose();            
return dt;

  

C#中连接数据库及操作的例子(转)

标签:

原文地址:http://www.cnblogs.com/nightsnow/p/4788362.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!