获取SQL数据并显示在一个文本框?文本框、数据、SQL

2023-09-03 16:48:54 作者:我的坟墓欢迎你

在过去的几天里,我想从我的SQL表中获取数据,并把它变成我的文本框。

表名:检查。

我使用的code:

  SqlDataReader的myReader = NULL;

连接=新的SqlConnection(System.Configuration.ConfigurationManager
                    .ConnectionStrings [的ConnectionString]的ConnectionString)。
connection.Open();

VAR命令=新的SqlCommand(SELECT * FROM [检查],连接);
myReader = Command.ExecuteReader却();
而(myReader.Read())
{
    TextBox1.Text = myReader.ToString();
}
的Connection.close();
 

我得到什么结果。任何人都知道为什么吗?也许我不是调用SQL是否正确?

解决方案

 使用(VAR连接=新SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
使用(VAR命令= connection.CreateCommand())
{
    command.CommandText =SELECT的ColumnName从[查询];
    connection.Open();
    使用(VAR读卡器= Command.ExecuteReader却())
    {
        而(reader.Read())
            TextBox1.Text =读卡器[的ColumnName]的ToString()。
    }
}
 
急需 在文本框输入内容然后点击查询按钮调出sql数据库数据并在GridView中显示所有数据

一些评论:

请不要使用 * ,仅指定需要这些领域 使用使用 - 少code,保证处置 我想这是一个测试程序,否则就没有意义重置文本到中环

In the last few days I am trying to get data from my SQL table and get it into my textbox.

The table name : "check".

The code I am using :

SqlDataReader myReader = null;

connection = new SqlConnection(System.Configuration.ConfigurationManager
                    .ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();

var command = new SqlCommand("SELECT * FROM [check]", connection);
myReader = command.ExecuteReader();
while (myReader.Read())
{
    TextBox1.Text = myReader.ToString();
}
connection.Close();

I am getting nothing as a result. Anyone know why? Maybe I am not calling the SQL correctly?

解决方案

using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var command = connection.CreateCommand())
{
    command.CommandText = "SELECT ColumnName FROM [check]";
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
            TextBox1.Text = reader["ColumnName"].ToString();
    }
}

Some comments:

don't use *, specify only those fields that you need use using - less code, guaranteed disposal I assume this is a test program, otherwise it does not make sense to reset Text to a in the loop