Oledb连接字符串未初始化
本文关键字:初始化 字符串 连接 Oledb | 更新日期: 2023-09-27 18:01:48
namespace PCMS
{
public partial class frmPlayerInterface : Form
{
private OleDbConnection con = new OleDbConnection();
OleDbCommand com = new OleDbCommand();
private DataTable dt = new DataTable();
public frmPlayerInterface(string getUser)
{
InitializeComponent();
con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:'Projects'SDP'PCMS'SDP.accdb";
lblUser.Text = getUser;
}
private void btnEnquire_Click(object sender, EventArgs e)
{
frmEnquire frmenq = new frmEnquire();
frmenq.ShowDialog();
}
private void btnTopUp1_Click(object sender, EventArgs e)
{
frmTopUp frmTU = new frmTopUp();
frmTU.ShowDialog();
}
private void frmPlayerInterface_Load(object sender, EventArgs e)
{
con.Open();
OleDbCommand comm = new OleDbCommand();
String sql = "select Balance from PlayerAccount where Player_User=@user";
comm.Parameters.Add(new OleDbParameter("user", lblUser.Text));
comm.CommandText = sql;
OleDbDataReader cursor = comm.ExecuteReader();
while (cursor.Read())
{
lblBalance.Text = cursor["Balance"].ToString();
}
con.Close();
}
}
}
嘿,抱歉伙计们又问这个问题了,但是我已经试了三个小时了,挥舞着白旗。仍然得到相同的错误
我只想从数据库中选择的余额值显示在标签中。
> & lt;感谢
您没有将连接与命令对象关联:
con.Open();
String sql = "select Balance from PlayerAccount where Player_User=@user";
OleDbCommand comm = new OleDbCommand(sql, con);
注意,重用连接并不总是最好的设计。连接是在。net中池化的,因此重新创建它们通常不是一个昂贵的操作。一个更好的设计是将连接字符串存储为一个类属性,然后在需要的时候创建一个连接:
private string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:'Projects'SDP'PCMS'SDP.accdb";
// or better yet - pull form app.config...
使用时:
String sql = "select Balance from PlayerAccount where Player_User=@user";
using(OleDbConnection con = new OleDbConnection(ConnectionString))
{
con.Open();
using(OleDbCommand comm = new OleDbCommand(sql, con))
{
... Add parameters, execute query, return results
}
}