我必须创建一个自动柜员机应用程序来访问一个包含样本客户记录的数据库。我在comboBox中显示accountInformation表(数据库)中的帐号时遇到问题。我很确定我正确地创建了数据库连接,我认为我的代码会在comboBox中显示数字,所以我不确定问题是什么。我需要更改comboBox属性中的某些内容吗? 这是我的代码:
using SQLDll;
namespace WindowsFormsApplication14
{
public partial class Form1 : Form
{
private Connection myConnection;
private Statement myStatement;
private ResultSet myResultSet;
String databaseURL = "http://www.boehnecamp.com/phpMyAdmin/razorsql_mysql_bridge.php";
public Form1()
{
InitializeComponent();
try
{
//connect to database
SQL sql = new SQL();
myConnection = sql.getConnection(databaseURL);
//create Statement for executing SQL
myStatement = myConnection.createStatement(databaseURL);
}
catch (Exception)
{
Console.WriteLine("Cannot connect to database server");
}
//close statement and database connection
myStatement.close();
myConnection.close();
}
private void Form1_Load(object sender, EventArgs e)
{
loadAccountNumbers();
}
public void setText(string text)
{
}
//load account numbers to ComboBox
private void loadAccountNumbers()
{
//get all account numbers from database
try
{
myResultSet = myStatement.executeQuery("SELECT accountNumber FROM accountInformation");
// add account numbers to ComboBox
while (myResultSet.next())
{
accountNumberComboBox.Items.Add(myResultSet.getString("accountNumber"));
}
myResultSet.close(); // close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in loadAccountNumbers");
}
}//end method to loadAccountNumbers
答案 0 :(得分:0)
我建议将所有内容都放在一个方法中。它更具可读性,即使发生异常,您也可以确保一切都关闭。
公共部分类Form1:表单 { private Connection myConnection; 私人声明myStatement; private ResultSet myResultSet; String databaseURL =“http://www.boehnecamp.com/phpMyAdmin/razorsql_mysql_bridge.php”;
public Form1()
{
InitializeComponent();
loadAccountNumbers();
}
//load account numbers to ComboBox
private void loadAccountNumbers()
{
SQL sql = new SQL();
using (myConnection = sql.getConnection(databaseURL))
using (myStatement = myConnection.createStatement(databaseURL))
using (myResultSet = myStatement.executeQuery("SELECT accountNumber FROM accountInformation"))
{
// add account numbers to ComboBox
while (myResultSet.next())
accountNumberComboBox.Items.Add(myResultSet.getString("accountNumber"));
}
}
答案 1 :(得分:0)
我发现了什么问题。我知道我必须在某处调用loadAccountNumbers(),但我不知道在哪里。我把它放在公共Form1()中,这解决了我的问题!感谢您的帮助。