windows console application链接数据库读取数据
长时间写asp.net代码,突然间想用consoleapplication连接数据库试试,自娱自乐,结果也学到了不少东西。
建表吧:
CREATE TABLE users( [ename] [nvarchar](20) NOT NULL PRIMARY KEY, [empno] [int] NOT NULL, )
配置app.config吧:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="dbcon" connectionString="Data Source=.;Database=sfzh;User ID=sa;Password=admin123;"/> </connectionStrings> </configuration>
有意思,突然间发现configuration这个类不智能提示了,捣鼓半天发现自己犯了个低级错误,竟然没有引用configuration.dll
O(∩_∩)O~
cs代码粘来吧:
using System.Data.SqlClient; using System.Data; using System.Configuration; //仅用using引用configuration是不行的,dll要引用 string strcon = ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString.ToString(); using (SqlConnection conn = new SqlConnection(strcon)) { string sql="select * from users"; using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { Console.WriteLine(sdr[0].ToString() + "\t" + sdr[1].ToString()); } } Console.ReadKey(); } }
ok了,吸取教训啊,粗心。。。
-------------------------------------------------
保持专注,只做一件事,做好这件事!@
-------------------------------------------------