码迷,mamicode.com
首页 > 数据库 > 详细

c#数据库连接学习

时间:2017-11-14 11:26:01      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:show   nbsp   exce   info   mes   while   获取   winform   end   

/*通过C#winform程序访问数据库数据

用到的命名空间和变量类型:

using System.Data.SqlClient;

SqlConnection;数据库连接类

SqlCommand;数据库操作类

SqlDataReader:读取 */

//登录按钮代码
private void button1_Click(object sender, EventArgs e) 
{
if (textBox1.Text == "")
MessageBox.Show("用户名不能为空!", "提示");
else if (textBox2.Text == "")
MessageBox.Show("密码不能为空!", "提示");
try //try...catch...异常处理语句
{
string name, pass;
bool flag = false;
name = textBox1.Text;
pass = textBox2.Text; //获取用户名,密码
string str = "Data Source=SQL服务器名称;Initial Catalog=数据库名;User ID=登录名;Password=密码;";
SqlConnection myConn = new SqlConnection(str);//创建数据库连接类的对象
myConn.Open(); //将连接打开
//SQL语句:从数据库的登录表中搜索登录名,密码
string sqlstring = "select username,password from users where username=‘" +name + "‘and password=‘" + pass + "‘"; 
//执行con对象的函数,返回一个SqlCommand类型的对象
SqlCommand command = new SqlCommand(sqlstring, myConn);
//用cmd的函数执行语句,返回SqlDataReader对象thisReader,thisReader就是返回的结果集(也就是数据库中查询到的表数据)
SqlDataReader thisReader = command.ExecuteReader();
//判断用户名及密码是否正确,对flag进行赋值
while (thisReader.Read()) 
{
if ((thisReader.GetValue(0).ToString().Trim()) == (name.ToString().Trim()))
{
if (thisReader.GetValue(1).ToString().Trim() == pass.ToString().Trim())
{
flag = true;
}
}
}
//用完后关闭连接,以免影响其他程序访问
myConn.Close(); 
if (flag)
{
MessageBox.Show("登陆成功!");
Form2 F = new Form2(); //显示主页面
F.Show();
this.Hide();
}
else
{
MessageBox.Show("请检查你的用户名和密码!");
textBox1.Focus();
}
}
catch (Exception ex2)
{
MessageBox.Show("连接远程SQL数据库发生错误:" + ex2.ToString(), "错误!");
}

 

 

 

 

转发自:http://www.cnblogs.com/q1092813103/p/5655881.html

c#数据库连接学习

标签:show   nbsp   exce   info   mes   while   获取   winform   end   

原文地址:http://www.cnblogs.com/shenghuizhang/p/7830769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!