c# 操作数据库

时间:2023-08-23 21:54:56

查询

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());
}