C# 连接 SQLServer 及操作
随笔:
连接:
// 将tb_User表数据添加到DataGridView中
string sqlconn = "Data Source=localhost;Initial Catalog=db_QQ;Persist Security Info=True;User ID=sa;Password=99990000"; SqlConnection conn = new SqlConnection(sqlconn); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT * FROM tb_User"; SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet();
// "user" 可改为任意字符串(-空串) sda.Fill(ds, "user"); conn.Close(); dataGridView1.DataSource = ds.Tables["user"];
向SQLServer插入数据(占位符和不使用占位符):
// 不使用占位符
cmd.CommandText = "INSERT INTO tb_User(IP, Port, Name, Password, State) VALUES(1, 1, 1, 1, 1)"; cmd.ExecuteNonQuery();
// 使用占位符 cmd.CommandText = "INSERT INTO tb_User(IP, Port, Name, Password, State) VALUES(@IP, @Port, @Name, @Password, @State)"; cmd.Parameters.AddWithValue("@IP", "2"); cmd.Parameters.AddWithValue("@Port", "2"); cmd.Parameters.AddWithValue("@Name", "2"); cmd.Parameters.AddWithValue("@Password", "2"); cmd.Parameters.AddWithValue("@State", "2"); cmd.ExecuteNonQuery();
查询数据
cmd.CommandText = "SELECT * FROM myqq_user"; // 使用 SqlCommand 和 SqlDataReader 读取数据 // Read(): 读取当前结果集的下一条记录,如果有,返回true,否则返回false // NextResult(): 读取下一个结果集,如果有返回true,否则返回false SqlDataReader sdr = cmd.ExecuteReader(); // HasRows 属性可以判断是否查询到数据 if (sdr.HasRows) { Console.WriteLine("有数据"); } do { Console.WriteLine("Result set"); while (sdr.Read()) { Console.Write(sdr.GetInt32(0)); Console.Write(" "); Console.Write(sdr.GetString(1)); Console.Write(" "); // 通过列名得到字段数据 Console.WriteLine(sdr.GetString(sdr.GetOrdinal("password"))); } } while (sdr.NextResult());