3

我是 C-Sharp 的新手,我正在尝试从 C-Sharp 访问我的数据库,我编写了以下代码,但我不知道接下来要写什么来查看数据。我在网上搜索过这个,但没有得到太多。请用简单的代码告诉我。

string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";

OleDbConnection conn = new OleDbConnection(connection);
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);

OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.SelectCommand = cmd;
4

2 回答 2

8

参考以下代码:

string strProvider = "@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;

希望它有帮助。

于 2013-04-09T11:39:36.750 回答
0

试试这个

        try
        {

        Dataset myDataSet=new Dataset();

        string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
        OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
        OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd );

        connection .Open();
        myDataAdapter.Fill(myDataSet,"TableName");

        }
        catch (Exception ex)
        {
              Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
              return;
        }
        finally
        {
              connection .Close();
        }

请记住良好的编码习惯,始终应在Try Block中打开连接并在finally Block 中关闭

于 2013-04-09T11:41:43.243 回答