日期:2014-05-18 浏览次数:21011 次
在配置文件web.config里添加 <Connectionstring > <add name="strConn" connectionString="server=服务器地址;database=数据库名;uid=登录名称;pwd=密码" / > </Connectionstring > //取得连接字符串 string strCn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; //获得数据 public DataTable getData() { DataTable dt = new DataTable(); SqlConnection sqlCn = new SqlConnection(strCn ); SqlCommand sqlCmd = new SqlCommand("select * from 表名",sqlCn ); SqlDataAdapter sqlAda = new SqlDataAdapter(sqlCmd ); try { sqlCn.Open(); sqlCmd.ExecuteNonQuery(); sqlAda.Fill(dt); sqlCn.Close(); } catch (Exception ex) { throw (ex); } return dt; } 要是用存储过程并有参数的话. //如获得图书信息 public DataTable getBook(int bookid) { DataTable dt = new DataTable(); SqlConnection sqlCn = new SqlConnection(strCn ); SqlCommand sqlCmd = new SqlCommand("getRecored",sqlCn ); sqlCmd.CommandType=CommandType.StoredProcedure; sqlCmd.Parameters.Add("@bookid",SqlDbType.Int,4); sqlCmd.Parameters["@bookid"].Value=bookid; SqlDataAdapter sqlAda = new SqlDataAdapter(sqlCmd ); try { sqlCn.Open(); sqlCmd.ExecuteNonQuery(); sqlAda.Fill(dt); sqlCn.Close(); } catch (Exception ex) { throw (ex); } return dt; }
------解决方案--------------------
写C#代码前要引用
using System.Data.SqlClient;
命名空间.