[英]How to improve SQL query by selecting row
I would like to improve my SQL query by selecting ROW 我想通过选择ROW来改进我的SQL查询
When I use 当我使用
cmd.CommandText = "SELECT user FROM users";
in my code, I have an error in line 在我的代码中,我遇到了一个错误
FillComboBox(dr["user"].ToString());
Column user does not belong to the table.
列用户不属于该表。
Original code, which works 原始代码有效
public void ReadUsersInfo(string connectionString)
{
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM users";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
FillComboBox(dr["user"].ToString());
}
Console.Read();
conn.Close();
}
user
is a keyword that returns the database user name of the current user. user
是返回当前用户的数据库用户名的关键字。 For example, select user
on my database returns dbo
. 例如,我数据库中的
select user
返回dbo
。
The query below selects this context as a column without a name: 下面的查询选择此上下文作为不带名称的列:
SELECT user FROM users
(No column name)
================
dbo
To return a column that has the same name as a keyword, you will need to escape it with brackets: 要返回与关键字同名的列,您需要使用方括号将其转义:
SELECT [user] FROM users
First of all, you are executing unnecessary commands. 首先,您正在执行不必要的命令。 When using data adapter:
使用数据适配器时:
Second, check if you are passing the right connection string - ensure you are connecting to the database of the image, not some other that has the table 'users' but not the column 'user'. 其次,检查您是否传递了正确的连接字符串-确保您正在连接到图像的数据库,而不是连接到具有表'users'而不是表'user'的其他数据库。
Third, and last, based on your image the table and column exists, so the code below has to work. 第三,也是最后,根据您的图像,表和列存在,因此下面的代码必须起作用。
public static void ReadUsersInfo(string connectionString)
{
const string query = "select [user] from dbo.users";
using (var dataTable = new DataTable())
{
using (var sqlConnection = new SqlConnection(connectionString))
{
using (var dataAdapter = new SqlDataAdapter(query, sqlConnection))
{
dataAdapter.Fill(dataTable);
}
}
foreach (DataRow dr in dataTable.Rows)
{
Console.WriteLine(dr["user"].ToString());
}
}
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.