获取SQL数据并显示在一个文本框? [英] Get SQL data And show it in a text box?

查看:141
本文介绍了获取SQL数据并显示在一个文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几天里,我想从我的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()。
    }
}
 

一些评论:

  • 请不要使用 * ,仅指定需要这些领域
  • 使用使用 - 少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

这篇关于获取SQL数据并显示在一个文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆