有没有更好的方法来使用不同的SQL查询进行提取?
还添加了代码段(虽然与我的问题没有关系)。
从INFORMATION_SCHEMA.COLUMNS中选择*,其中TABLE_SCHEMA = ' $ schema_name $',TABLE_NAME =' $ table_name $&#39 ;;
public TableStructure GetTableStructure(string TableName, MySqlConnection Connection)
{
if (Connection == null)
throw new ArgumentNullException("Sql Connection should be initialized.");
string sqlQuery = @"select * from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA = '$schema_name$', TABLE_NAME='$table_name$'";
sqlQuery = sqlQuery.Replace("$table_name$", TableName);
sqlQuery = sqlQuery.Replace("$schema_name$", SchemaName);
TableStructure tableStructure = null;
try
{
using (MySqlCommand sqlCmd = new MySqlCommand(sqlQuery, Connection))
{
if (Connection.State == ConnectionState.Closed)
Connection.Open();
using (MySqlDataReader dr = sqlCmd.ExecuteReader())
{
while (dr.Read())
{
...
...
//tableStructure = TableStructure.GetTableStructureFromDataReader(TableName, dr);
}
}
}
}
catch (Exception)
{
//TODO
throw new Exception("Error occured while obtaining tables list");
}
return tableStructure;
}
答案 0 :(得分:3)
具有多个条件的WHERE语句需要AND / OR才能加入这两个条件
string sqlQuery = @"select * from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = '$schema_name$' AND TABLE_NAME='$table_name$'";
而不是使用REPLACE设置字符串值(a dangerous practice如果输入是由最终用户直接输入的话),您可以使用参数化查询
string sqlQuery = @"select * from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = @schema AND TABLE_NAME=@table";
using (MySqlCommand sqlCmd = new MySqlCommand(sqlQuery, Connection))
{
sqlCmd.Parameters.AddWithValue("@schema", SchemaName);
sqlCmd.Parameters.AddWithValue("@table", TableName);
.....