回答

收藏

获取SQL并在文本框中显示数据?

技术问答 技术问答 84 人阅读 | 0 人回复 | 2023-09-13

最近几天,我试图从SQL在表中获取数据,并将其放入文本框中。
& v; w8 W' s: {& e* P名称:检查。8 }+ a4 n* u3 S( i) N% {# B) S& D
我使用的代码:
8 \! E, T8 n# w0 `( [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();结果我什么也没得到。有人知道为什么吗?也许我没有正确调用它。SQL?
6 X# J6 `# S6 v4 O9 ]- ?& \* j                                                                / Q5 t2 |' ?' `
    解决方案:                                                               
9 b1 q: z: l- e' M- h8 `8 T4 s5 w                                                                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();     }}一些评论:
! i1 U, M1 \8 _( C. m6 M不要使用*,指定你需要的字段
# _5 B" K7 Z3 [' ^/ m使用using-代码少,保证处理2 y) Q/ }( L: Y% o# C
我假设这是一个测试程序,否则Text在循环中重置为无意义
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则