美文网首页
使用C#windows应用程序实现登录界面(连接SQL Serv

使用C#windows应用程序实现登录界面(连接SQL Serv

作者: 简段 | 来源:发表于2016-10-12 19:54 被阅读0次

    经历了万般周折之后C#终于奇迹般的远程连接上了数据了。

    1、实现C#控制台应用程序连接远程SQL服务器

    SqlConnection myConnection;

    //创建连接数据库的字符串

    // 注意下面的设置,server 数据库服务器名称;database 要连接的数据库名称 uid 登录名 Pwd 登录密码

    string connStr = "Server =219.216.73.145 ;database = ieLAB;uid = sa;pwd =123";

    myConnection = new SqlConnection(connStr);  //构造myConnection对象

    try

    {

    myConnection.Open();  //连接数据库

    }

    catch (Exception e)

    {

    Console.WriteLine("{0} Second exception caught.", e);  //发生错误后,抛出出错原因。

    Console.ReadLine();

    }

    Console.WriteLine("连接成功!");  //显示连接成功

    myConnection.Close();  //关闭数据库连接

    Console.ReadLine();

    2、用C#windows应用程序实现登录界面(挂远程SQL)

    注:输入用户名和密码,与数据库所存数据进行匹配,匹配成功进入下一界面Form2,不成功提示“用户名或密码错误!”


    所需控键:2 Lable  2 TextBox  1button

    具体代码:

    using System.Data.SqlClient;

    private void 登录_Click(object sender, EventArgs e)

    {

    string str = "Server =219.216.73.145 ;database = Test;uid = sa;pwd =123";

    SqlConnection conn = new SqlConnection(str);

    try

    {

    conn.Open();

    string sql = "select * from myTest where UserID='" + txt_ID.Text + "'and Password='" + txt_password.Text + "'";

    SqlCommand cmd = new SqlCommand(sql, conn);

    cmd.CommandType = CommandType.Text;

    SqlDataReader sdr = cmd.ExecuteReader();

    if (sdr.Read())

    {

    Form2 f2 = new Form2();

    f2.Show();

    }

    else

    {

    MessageBox.Show("账户或密码有误!");

    }

    }

    catch (Exception a)

    {

    Console.WriteLine("{0} Second exception caught.", a); //发生错误后,抛出出错原因

    Console.ReadLine();

    }

    }

    相关文章

      网友评论

          本文标题:使用C#windows应用程序实现登录界面(连接SQL Serv

          本文链接:https://www.haomeiwen.com/subject/lgwiyttx.html