关于数据库连接问题首先是进行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);
}
}