winform-Database Connection

Source: Internet
Author: User

1. Start service: SQL Server Configuration

2.windows authentication into the SQL server-security-sa-Password change;

3. New database Booksystem;

4.public Partial class Form1:form

{

SqlConnection Conn;

Public Form1 ()

{

InitializeComponent ();

}

private void Btnlogin_click (object sender, EventArgs e)

{

Try

{

Conn. Open ();

MessageBox.Show (Conn. State.tostring ());

}

catch (Exception ex)

{

Friendly Tips

MessageBox.Show (ex. message);

Throw ex;

}

finally {

Conn. Close ();

MessageBox.Show (Conn. State.tostring ());

}

}

private void Form1_Load (object sender, EventArgs e)

{

conn = new SqlConnection ("server=.; Database=booksystem;uid=sa;pwd=sa ");

}

}

5.sql

String sqlstr = "SELECT * from admin where admname= ' lyc ' and admpwd= ' 123 '";

Trim () Remove space on both sides

String sqlstr = @ "SELECT * FROM admin"

where admname= ' "+ this.txtName.Text.Trim () +" ' and admpwd= ' "+ this.txtPwd.Text.Trim () +" ' ";

cmd = new SqlCommand (SQLSTR, conn);

Conn. Open ();

Object Obj=cmd. ExecuteScalar ();

Try

{

//

Int32 count = (Int32) cmd. ExecuteScalar ();

int count = (int) cmd. ExecuteScalar ();

MessageBox.Show ("correct");

}

catch (Exception ex)

{

MessageBox.Show ("Incorrect username password");

Throw ex;

}

finally {

Conn. Close ();

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.