一,初始化数据库连接
define是类,定义全局变量
Define.connectstring = "Data Source=105.147.202.11;Initial Catalog=clearer;User ID=**;Password=*************.";
Define.sqlConnection = new SqlConnection(Define.connectstring);
二,确认数据库是否打开
if (Define.sqlConnection.State.Equals(ConnectionState.Closed))//判断当前数据库状态,是否打开
Define.sqlConnection.Open();
SqlCommand SqlCom = new SqlCommand(); //新建了命令类
string execstring;
execstring = "select 用户密码 from table1 用户名='" + username + "'"; //SQL控制语句,username是外部变量
SqlCom.Connection = Define.sqlConnection; //连接地址 SqlCom.CommandText = execstring; //控制命令 SqlCom.ExecuteNonQuery(); //执行命令 SqlDataReader dataReader = SqlCom.ExecuteReader(); //定义读取流 if (dataReader.Read()) { password = Convert.ToString(dataReader[0]); //读取返回数组第一列,即用户密码列第一个 dataReader.Close(); Define.sqlConnection.Close(); //关闭 return password; //返回获得的用户密码 } else { dataReader.Close(); Define.sqlConnection.Close(); password = "查找无此用户"; return password; }