使用OleDbConnection如何连接到Access中包含20个单词的表,然后让它从表中随机选择一个单词并将其存储在表单上的标签中?
public partial class MainForm : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\WordsDB.accdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void MainForm_Load(object sender, EventArgs e)
{
String command = "SELECT * FROM Words";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
DisplayRow(currentRecord);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the datatable with the rows reurned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
WordsLbl.Text = row["SpellingWords"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
}
正如您所看到的,这是代码,我想要了解的是,如何从数据库中的表中获取随机单词并将其存储在标签中?另外,我正在使用OleDbConnection来连接数据库!
答案 0 :(得分:0)
您可以在AsEnumerable
上使用DataTable
,然后您可以在其中选择一个随机字词。例如,填写数据表之后:
FillDataTable(command);
var words = myDataTable.AsEnumerable()
.Select(d => d["word"].ToString())
.ToList();
Random rnd = new Random();
int randomNumber = rnd.Next(0, words.Count + 1);
string randomWord = words[randomNumber];
label1.Text = randomWord;
这应该可行。您应该在此行中使用您的列名更改word
:.Select(d => d["word"].ToString())
答案 1 :(得分:0)
在我的答案中查看“拒绝修改”之后,以下是适用于原始问题的部分:
您可以尝试使用“随机”类生成如下随机数:
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
至于为什么你的程序没有工作(在评论中提到),我推荐了以下内容:
我将您的代码复制并粘贴到新项目中,并按照您的描述创建了一个Access数据库......我相信您遇到的问题是:
问题一:你的程序没有找到“WordsDB.accdb”。
可能的解决方案:
(1)你可以弄清楚如何创建正确的| DataDirectory | “连接字符串”或
中的路径(2)将您的“WordsDB.accdb”放在一个文件夹中,您可以使用完整路径引用该文件夹,如“Data Source = C:\ inetpub \ wwwroot \ app_data \ WordsDB.accdb ”所以你的“连接字符串”如下所示:
private const String access7ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
问题二:您需要将随机代码移出当前位置,以便在填充DataTable后执行它。
可能的解决方案:
(1)将Form1.cs更改为如下所示:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\app_data\WordsDB.accdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void MainForm_Load(object sender, EventArgs e)
{
String command = "SELECT * FROM Words";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
/* Move this "DisplayRow(currentRecord);" down below and use
after you get a random number to pick a random word as shown
below... */
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// =========== Get a Random Number first, then call DisplayRow() ===============
// Figure out the upper range of numbers to choose from the rows returned
int maxCount = myDataTable.Rows.Count;
// generate a random number to use for "rowIndex" in your 'myDataTable.Rows[rowIndex]'
Random randomNR = new Random();
int myRndNR = randomNR.Next(0, maxCount - 1);
// Execute your DisplayRow(int rowIndex) using myRndNR
DisplayRow(myRndNR);
// ===========
}
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the DataTable with the rows returned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
WordsLbl.Text = row["SpellingWords"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
public Form1()
{
InitializeComponent();
}
}
}
潜在问题:
您可能没有将表单设置为执行的“事件,行为,加载”
MainForm_Load
潜在解决方案:
一个。转到Visual Studio中的“设计视图”,然后右键单击“表单”。
湾单击弹出窗口中的“属性”
℃。在“属性”窗口(可能在Visual Studio的右下角)中查找“事件”
d。找到“事件”后,查找“行为”(如果按“类别”排序属性)或“加载”(如果按字母顺序排序属性)
即在“加载”框中,确保它显示“MainForm_Load”
答案 2 :(得分:0)
由于您正在使用访问权限,因此一旦您的数据表填充了行,就可以执行此操作。在填充数据表之后,我已经能够测试这个。我从不同的数据库填充了我的数据表,但这没关系。我的代码的最后4行可以帮助您每次从数据表中获取随机记录。
{
const string query = "SELECT name FROM NewTable";
var command = new SqlCommand(){CommandText = query, CommandType = System.Data.CommandType.Text,Connection=sqlConn};
var dataAdapter = new SqlDataAdapter() { SelectCommand = command };
DataTable dataTable = new DataTable("Names");
dataAdapter.Fill(dataTable);
int count = dataTable.Rows.Count;
int index = new Random().Next(count);
DataRow d = dataTable.Rows[index];
Console.WriteLine(d[0]);
}