using System.Data;//引用数据库就能用到这句话
using System.Data.SqlClient; //连接数据库
string cId = textcId.Text.Trim();//从文本框提取文字
string cName = textcName.Text.Trim();
string cTeam = textcTeam.Text.Trim();
string cSlogan = textcSlogan.Text.Trim();
string connectionString = "server=.;database=StudentMIS;integrated security = true; ";//连接数据库的字符传
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();//执行连接
string sql = "insert into ClassMis values('{0}','{1}','{2}','{3}')";
sql = string.Format(sql, cId, cName, cTeam, cSlogan);//填充字符串
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
int couny = cmd.ExecuteNonQuery();//对连接执行sql语句,并返回受影响的行数
MessageBox.Show(couny.ToString());
}
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "select cName from ClassMis where cId = 1";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
Console.WriteLine(cmd.ExecuteScalar().ToString());//返回select的单个数据,第一行的第一个。
}
}
string connectionString = "server = .;database = StudentMIS;integrated security = true;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "select * from ClassMis";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)//判断数据是否为空
{
while (reader.Read())//判断是否读到数据
{
//
//1.效率最低,得先转换为[0][1][2],但很直白
//Console.Write(reader["cId"].ToString()+"\t");
//Console.Write(reader["cName"].ToString()+"\t");
//Console.Write(reader["cTeam"].ToString() + "\t");
//2.效率较高,顺序可调,但变化的顺序仍然是依照着数据库
//Console.Write(reader[0].ToString() + "\t");
//Console.Write(reader[1].ToString() + "\t");
//Console.Write(reader[2].ToString() + "\t");
//3.可以直接转换为自己想要的数据类型
//Console.Write(reader.GetInt32(0).ToString() + "\t");
//Console.Write(reader.GetString(1).ToString() + "\t");
//Console.Write(reader.GetValue(2).ToString() + "\t");
//4.在不知道数据列表情况下
//for (int i = 0; i < reader.FieldCount; i++)
//{
// Console.Write(reader[i].ToString() + "\t");
//}
//5.便利多个结果集
do
{
} while (reader.NextResult());
Console.WriteLine();
}
}
}
//connection.Close();//关闭连接,并解除占用。内部调用的Dispose。
//connection.Dispose();//解除占用数据,释放资源
1. cmd.ExecuteNonQuery();//对连接执行sql语句,并返回受影响的行数,可以进行update,delete
2.cmd.ExecuteScalar()://返回select的单个数据,第一行的第一个。
3.cmd.ExecuteReader();//返回的是一个sqlDataReader类型的数据,能输出表型数据
reader.HasRows)//判断数据是否为空
reader.Read())//判断是否读到数据