我正在制作一个简单的程序来将访问数据库更改为sql查询以导入到sql数据库中,获取列的名称没有问题但是当我尝试获取行的值时,它只会变成一个巨大的混乱。这是我的完整代码,以防我在某处出错:
string table = "";
List<object> cols = new List<object>();
List<string> stringArr = new List<string>();
private void button1_Click(object sender, RoutedEventArgs e)
{
src = srcTxt.Text;
table = tableCB.Text;
string output = outTxt.Text;
string scriptString = "";
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + src;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * FROM " + table, connection);
reader = command.ExecuteReader();
var tabName = reader.GetSchemaTable();
var nameCol = tabName.Columns["ColumnName"];
foreach (DataRow row in tabName.Rows)
{
cols.Add("`" + row[nameCol] + "`");
}
var result = string.Join(",", cols);
scriptString = "INSERT INTO `" + table + "` (" + result + ") VALUES \n";
int n = 0;
while (++n < tabName.Rows.Count)
{
stringArr.Add("reader.GetString(" + n + ")");
}
var strValue = string.Join(",", stringArr);
while (reader.Read())
{
scriptString += "(" + strValue + "),\n";
}
}
File.WriteAllText(output, scriptString += ";");
}
但仅代表行部分的代码:
int n = 0;
while (++n < tabName.Rows.Count)
{
stringArr.Add("reader.GetString(" + n + ")");
}
var strValue = string.Join(",", stringArr);
while (reader.Read())
{
scriptString += "(" + strValue + "),\n";
}
非常感谢一些建议:)
答案 0 :(得分:0)
我想你想要这个结果,我不确定。我希望这段代码可以帮助你
string table = "";
List<object> cols = new List<object>();
List<string> stringArr = new List<string>();
private void button1_Click(object sender, RoutedEventArgs e)
{
src = srcTxt.Text;
table = tableCB.Text;
string output = outTxt.Text;
string scriptString = "";
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + src;
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * FROM " + table, connection);
reader = command.ExecuteReader();
var tabName = reader.GetSchemaTable();
var nameCol = tabName.Columns["ColumnName"];
foreach (DataRow row in tabName.Rows)
{
cols.Add("`" + row[nameCol] + "`");
}
var result = string.Join(",", cols);
// scriptString = "INSERT INTO `" + table + "` (" + result + ") VALUES \n";
// int n = 0;
// while (++n < tabName.Rows.Count)
// {
// stringArr.Add("reader.GetString(" + n + ")");
// }
// var strValue = string.Join(",", stringArr);
// while (reader.Read())
// {
// scriptString += "(" + strValue + "),\n";
// }
while(reader.Read())
{
scriptString += "INSERT INTO `" + table + "` (" + result + ") VALUES \n (";
int n = 0;
while (++n < tabName.Columns.Count)
{
stringArr.Add(reader.GetValue(n).ToString());
}
var strValue = string.Join(",", stringArr);
scriptString += strValue + "); \n";
}
}
File.WriteAllText(output, scriptString += ";");
}