c# 操作数据库
查询
string strConnection = "Data Source=(local);Initial Catalog=zpractice;Integrated Security=SSPI";//windows认证 不提倡
SqlConnection sqlCon = new SqlConnection(strConnection);
sqlCon.Open();
string sql = "select * from dbo.users";
SqlCommand command = sqlCon.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
SqlDataReader reader = command.ExecuteReader();
while(reader.Read()){....}//逐行读取数据进行相关操作
更新 增加 删除
string strSql = "update users set password=@password where id=@id and name=@name ";
string strAdd="insert into dbo.users values (@username,@password)";
string strDelete="delete from users where id=@id";
//实例化SqlParameter对象,为@username等建立映射关系
SqlParameter userid = new SqlParameter("@id", context.Request.Form["hidUserId"].ToString());
SqlParameter username = new SqlParameter("@name",context.Request.Form["hidUserName"].ToString());
SqlParameter password = new SqlParameter("@password",strNewPwd);
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand(strSql,conn);
cmd.CommandType = CommandType.Text;
//将映射关系添加到cmd中
cmd.Parameters.Add(userid);
cmd.Parameters.Add(username);
cmd.Parameters.Add(password);
if (cmd.ExecuteNonQuery() > 0) //受影响数据条数
{
context.Response.Write("修改成功");
}
将数据库中数据添加到session中
sql = "select id from users where name=@name and password=@password";
cmd.CommandText = sql;
cmd.Parameters.Add(username);
cmd.Parameters.Add(password);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sqlAdapter.Fill(dt);
if (dt.Rows.Count>0)
{
context.Session.Add("userid",dt.Rows[0]["id"].ToString());
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。