连接数据库,并从数据库中读取数据后并输出!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace Login
{
class Program
{
static void Main(string[] args)
{
//新建一个数据库连接
using(SqlConnection conn = new SqlConnection(GetConnectString()))
{
conn.Open();//打开数据库
//Console.WriteLine("数据库打开成功!");
//创建数据库命令
SqlCommand cmd = conn.CreateCommand();
//创建查询语句
cmd.CommandText = "SELECT * FROM userinfo";
//从数据库中读取数据流存入reader中
SqlDataReader reader = cmd.ExecuteReader();
//从reader中读取下一行数据,如果没有数据,reader.Read()返回flase
while (reader.Read())
{
//reader.GetOrdinal("id")是得到ID所在列的index,
//reader.GetInt32(int n)这是将第n列的数据以Int32的格式返回
//reader.GetString(int n)这是将第n列的数据以string 格式返回
int id = reader.GetInt32(reader.GetOrdinal("id"));
string name = reader.GetString(reader.GetOrdinal("name"));
string pwd = reader.GetString(reader.GetOrdinal("password"));
int age = reader.GetInt32(reader.GetOrdinal("age"));
string sex = reader.GetString(reader.GetOrdinal("sex"));
string phone = reader.GetString(reader.GetOrdinal("phone"));
string address = reader.GetString(reader.GetOrdinal("Address"));
//格式输出数据
Console.Write("ID:{0},Name:{1},PWD:{2},Age:{3},Sex:{4},Phone{5},Address:{6}\n", id, name, pwd, age, sex, phone, address);
}
}
Console.ReadKey();
}
//得到一个数据库连接字符串
static string GetConnectString()
{
return "Data Source=(local);Initial Catalog=db1;Integrated Security=SSPI;";
}
}
}
只要说一下SQL语句?这样的话一楼的就是你要的答案了。不过你好像不只要SQL语句;以下贴代码:
string str1="select count from KuCun where num=值";
string str2="server=服务器名称;data=数据库名称;uid=登录名;pwd=登录密码";
sqlconnection con=new sqlconnection(str2);
con.Open();
if(con.state==connectionstate.open)
{
sqlDataAdapter chaxun=new sqlDataAdapter(str1,str2);
DataSet rongqi=new DataSet();
chaxun.Fill(rongqi);
int i=int.Parse(rongqi.Table[0].Rows[0].ToString());//在这里,i就被赋了查询出来的结果的第一行的 , //数据,此处是int类型,要其他类型自己转换, , //下就好了
}
select count from kucun where num = 你输入的值