日期:2014-05-18  浏览次数:21144 次

vs c#.net中调用数据库的问题
编写一个图书馆管理系统,图书信息和读者信息用数据库存储,窗口什么的用的c#,我通过工具->连接到数据库将数据库加到项目中了,可是不知道怎么用代码调用数据库中的记录。。。。。求高手指点。。。。。

------解决方案--------------------
http://www.cnblogs.com/aidd2008/archive/2008/12/05/1348695.html
http://www.360doc.com/content/11/0112/18/1947337_86028583.shtml
------解决方案--------------------
额 
1、在web.config 中配置数据库连接字符串
比如:
C# code

<add name="SQLConnString1" connectionString="server=(local);database=EpgInfo;user id=sa;password=sa;integrated security=SSPI;min pool size=4;max pool size=4;" providerName="System.Data.SqlClient"/>

------解决方案--------------------
数据库连接及访问常用几个对象和方法
class DataConn {
#region 建立数据库连接
/// <summary>
/// 建立数据库连接.
/// </summary>
/// <returns>返回SqlConnection对象</returns>
public SqlConnection getcon()
{
string M_str_sqlcon = "Data Source=MIAMI;Initial Catalog=db_crm;Integrated Security=SSPI;";
SqlConnection myCon = new SqlConnection(M_str_sqlcon);
return myCon;
}
#endregion

#region 执行SqlCommand命令
/// <summary>
/// 执行SqlCommand
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
public void getcom(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);
sqlcom.ExecuteNonQuery();
sqlcom.Dispose();
sqlcon.Close();
sqlcon.Dispose();
}
#endregion

#region 创建DataSet对象
/// <summary>
/// 创建一个DataSet对象
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
/// <param name="M_str_table">表名</param>
/// <returns>返回DataSet对象</returns>
public DataSet getds(string M_str_sqlstr, string M_str_table)
{
SqlConnection sqlcon = this.getcon();
SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlda.Fill(myds, M_str_table);
return myds;
}
#endregion

#region 创建SqlDataReader对象
/// <summary>
/// 创建一个SqlDataReader对象
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
/// <returns>返回SqlDataReader对象</returns>
public SqlDataReader getread(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);
sqlcon.Open();
SqlDataReader sqlread = sqlcom.ExecuteReader(CommandBehavior.CloseConnection);
return sqlread;
}
#endregion
}
用这个类的实例的方法来实现各种sql操作就可以啦

举例,登录按钮:
private void btnLogin_Click(object sender, EventArgs e)
{
SqlDataReader sqlread = boperate.getread("select UserName,UserPwd from tb_User where UserName='" + cboxUName.Text.Trim() + "' and UserPwd='" + txtPwd.Text.Trim() + "'");
sqlread.Read();
if (sqlread.HasRows)
{
M_str_name = cboxUName.Text;
M_str_pwd = txtPwd.Text.Trim();
frmMain fmain = new frmMain();
this.Hide();