gpt4 book ai didi

c# - 有没有更好的方法来获取表结构?

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:27 24 4
gpt4 key购买 nike

有没有更好的方法来使用不同的 SQL 查询来获取数据?

还添加了代码片段(虽然与我的问题并不相关)。

select * from INFORMATION_SCHEMA.COLUMNS where TABLE_SCHEMA = '$schema_name$', TABLE_NAME='$table_name$';

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;
}

最佳答案

具有多个条件的 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);
.....

关于c# - 有没有更好的方法来获取表结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22819719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com