天天看點

新手菜鳥潇關于winform資料庫連接配接問題

關于資料庫連接配接問題首先是進行config檔案的配置:

1.1.window身份驗證以及讀取字段:

<appSettings>

    <add key="ConnectString" value="server=.\sqlexpress;database=BBSDB;integrated security=sspi"/>

</appSettings>

其中integrated security是Microsoft安全支援提供器接口(sspi)定義得較全面的公用API,用來獲得驗證、資訊完整性、資訊隐私等內建安全服務;

==============

Integrated Security 身份驗證方式 

當為false時,将在連接配接中指定使用者ID和密碼。 

當為true時,将使用目前的Windows帳戶憑據進行身份驗證。 

可識别的值為true、false、yes、no以及與true等效的sspi。

==============

C#code

string comm = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

或者

1.2.SQL Server身份驗證:

<connectionStrings>

    <add name ="connection" connectionString="server=127.0.0.1;database=login;uid=sa;pwd=liandeng;" />

  </connectionStrings>

c#中讀取字段代碼:

string comm = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

其中記得添加引用system.webfiguration

2.

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string username = textBox1.Text.Trim();
                string password = textBox2.Text.Trim();
                if (username == "")
                {
                    MessageBox.Show("請輸入使用者名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (password == "")
                {
                    MessageBox.Show("請輸入密碼", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string comm = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;//讀取資料庫
                    SqlConnection con = new SqlConnection(comm);//進行連接配接;
                    con.Open();//打開資料庫;
                    SqlCommand com = new SqlCommand();//建立資料庫指令,才可以進行增删查改;
                    com.Connection = con;
                    com.CommandType = CommandType.Text;//讀取SQL文本;
                    com.CommandText = "select count(*) from login where name='" + username + "' and password='" + password + "'";
                    //查詢語句;
                    //SqlDataReader dr = com.ExecuteReader();//進行查詢傳回所有值;
                    int n = (int)com.ExecuteScalar();//進行查詢傳回第一行;
                    if (n > 0)
                    {
                        //dr.Close();
                        con.Close();
                        MessageBox.Show("登陸成功!");
                    }
                    else
                    {
                        MessageBox.Show("使用者名或密碼錯誤", "警告", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }