欢迎来到unity学习、unity培训
这里有很多U3D资源、U3D培训视频、U3D教程、U3D常见问题、U3D项目源码,我们致力于打造业内unity3d培训、学习第一品牌
控制台调用数据库的基本语句:
使用数据库的顺序:
1、引入命名空间
2、创建一个SqlConnection对象(连接数据库的语句)
3、打开连接
4、创建一个SqlCommand对象(要执行的语句)
5、获取SqlDataReader对象
6、关闭SqlDataReader对象
7、关闭连接
简单的增删改用不到SqlDataReader对象,所以5、6步可以不写
增删改:
//这个是一个插入的方法
public int StudentRagister(string name,string password,string sex)
//参数是用来执行数据库语句的,因为要插入自己输入的语句,所以要用到参数
{
SqlConnection con = new SqlConnection("server=.;Trusted_Connection=SSPI;database=School");
//这句话是使用数据库是必写的语句,用来打开数据库用的
//(注:Trusted_Connection=SSPI这句话是windows平台的一个打开数据库的语句,用来代替使用密码登入数据库时的账号密码用的,server是要求输入服务起名,database是数据库名)
string sql = "insert into Student(name,password,sex) values ('" + name + "','" + password + "','" + sex + "')";
//用string类型保存下将要执行的sql语句,把你需要的参数写进去,特别要注意空格,有的时候不会报错,就是无法执行
SqlCommand com = new SqlCommand(sql, con);
//将写好的sql语句带入数据库执行
con.Open(); //打开连接
int i = com.ExecuteNonQuery();
//com.ExecuteNonQuery();可以返回受影响的行数,看以判断你的Sql语句是否被执行了
con.Close(); //关闭连接
return i;
}
//删除、修改和插入的写法差不多,不同的就是sql语句不通。
查询:
这个是用迭代器查询表中所有的数据并输出
public List<Student> Users()
{
List<Student> list=new List<Student>();
SqlConnection con = new SqlConnection("server=.;Trusted_Connection=SSPI;database=School");
string sql = "select *from Student";
SqlCommand com = new SqlCommand(sql, con);
con.Open();
//这里到上面和插入相差不多,不同的是讲集合当这个方法属性。
SqlDataReader re = com.ExecuteReader();
//可以返回一个对象
//通过while和集合把数据库里的数据传出来
while (re.Read())
{
Student a = new Student();
a.Id = (int)re.GetValue(0);
a.Name = (string)re.GetValue(1);
a.Password = (string)re.GetValue(2);
a.Sex = (string)re.GetValue(3);
list.Add(a);
}
//最后foreach便利输出所有的数据
foreach (Student b in list)
{
Console.WriteLine("ID:" + b.Id + " 名字:" + b.Name + " 密码:" + b.Password + " 性别:" + b.Sex);
}
return list;
}
这个返回值是集合,所以开控制台端也要弄个集合
还有一种用来查询一行信息比较好用,可以用在登入上面
public bool StudentLongin(string name,string password)
通过参数得到两个数值,查找数据库里两个数据都正确的那一行
{
bool fla = false;
让这个bool类型一开始就为假
SqlConnection con = new SqlConnection("server=.;Trusted_Connection=SSPI;database=School");
string sql = "select *from Student where name='" + name + "' and password='" + password + "'";
SqlCommand com = new SqlCommand(sql, con);
con.Open();
SqlDataReader re = com.ExecuteReader();
while (re.Read())
{
fla = true;
//重点就在这里,当有数值能被使用时,让其变成true,
}
con.Close();
re.Close();
return fla;
//到这里能够只返回是真还是假,就能判断有没有哪行数据
}