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();
}
}
}
嘿抱歉的人再次问这个问题,但是我在过去的三个小时里一直试着这个并挥动白旗。仍然得到同样的错误。
我只想让数据库中选定的余额值显示在标签中。
谢谢><
答案 0 :(得分:1)
您没有将连接与命令对象关联起来:
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
}
}