我正在尝试编写一个从Access表创建.csv文件的程序。我不确定如何做到这一点以及我在研究这个时发现的一切是如何做到相反,从.csv文件创建一个Access表。
到目前为止,我已经创建了一个Windows窗体应用程序,允许用户选择访问目录(.mdb)的数据路径,然后在按下“开始”按钮后,显示目录中的表列表在列表框中。
接下来我需要做的是允许用户选择其中一个表,然后从选定的表创建一个.csv文件。到目前为止,这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
namespace TranslatorHelper
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPath_Click(object sender, EventArgs e)
{
string dialogText = "";
// Show the dialog and get result.
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
dialogText = openFileDialog1.ToString();
dialogText = dialogText.Replace("System.Windows.Forms.OpenFileDialog: Title: , FileName: ", "");
txtDataPath.Text = dialogText;
}
}
private void btnGetTables_Click(object sender, EventArgs e)
{
// Microsoft Access provider factory
DbProviderFactory factory =
DbProviderFactories.GetFactory("System.Data.OleDb");
DataTable userTables = null;
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+txtDataPath.Text;
// We only want user tables, not system tables
string[] restrictions = new string[4];
restrictions[3] = "Table";
connection.Open();
// Get list of user tables
userTables = connection.GetSchema("Tables", restrictions);
}
// Add list of table names to listBox
for (int i = 0; i < userTables.Rows.Count; i++)
lstTables.Items.Add(userTables.Rows[i][2].ToString());
}
private void lstTables_SelectedIndexChanged(object sender, EventArgs e)
{
}
请提供任何建议,任何感激之情,我真的被困在这里。
答案 0 :(得分:3)
也许我可以把你推向正确的方向:
你有一个开始,即DbConnection。然后,您可以从中创建DbCommand:
DbCommand command = connection.CreateCommand();
从那里,您可以指定文本,例如:
command.CommandText = "SELECT * FROM " + tableName; //you might have to wrap the table name with quotes or square brackets!
然后你可以找一个读者:
DbDataReader reader = command.ExecuteReader(CommandBehavior.Default);
一旦你有了读者,你就拥有了数据,这意味着你可以:
DataTable dt = new DataTable("MyNewTable");
dt.Load(reader);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn dc in row.Columns)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append(",");
sb.Append(row[dc.ColumnName].ToString());
}
sb.Append("\n");
}
要获取ListBox选项,您可以使用:
lstTables.SelectedItem.ToString()
那应该给你这个项目,或者在你的情况下给你一个表名。不要忘记在SQL中保留某些单词(它还取决于它是哪个SQL),因此您可能必须小心地在SQL字符串中直接使用表名作为CommandText参数。
此外,我认为不需要使用SelectedIndexChanged事件处理程序,除非您需要在用户进行选择时立即执行某些操作。如果您希望用户执行选择,然后单击按钮以启动进程,则无需处理更改。