1.直接写数据库连接字符串
string constr = "server=.;database=myschool;integrated security=SSPI";//string constr = "server=.;database=myschool;uid=sa;pwd=sa";//string constr = "data source=.;initial catalog=myschool;user id=sa;pwd=sa";SqlConnection con = new SqlConnection(constr);// con.ConnectionString = constr;string sql = "select count(*) from grade";SqlCommand com = new SqlCommand(sql,con);try{ con.Open(); MessageBox.Show("成功连接数据库"); int x = (int)com.ExecuteScalar(); MessageBox.Show(string.Format("成功读取{0},条记录", x));}catch (Exception){ throw;}finally{ con.Close(); MessageBox.Show("成功关闭数据库连接", "提示信息", MessageBoxButtons.YesNoCancel);}
2.web.config配置
C#后台处理程序
string connectionString =ConfigurationManager.ConnectionStrings["myschool"].ConnectionString;
private string strCon = ConfigurationManager.AppSettings["ConnectionString"];