c#操作sqlserver数据库的简单示例
1.在用windows模式登陆sql server 数据库 简历一个student的数据库,然后新建查询:
create table student
(
id int auto_increment primary key,
name char(10) not null,
sex char(10) not null,
age char(10) not null,
)
2.在vs中新建一个项目,输入一下代码:
using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using system.data;
using system.data.sqlclient;
namespace consoleapplication1
{
class program
{
static void main(string[] args)
{
string connsting;
connsting = "server=localhost;database=student;integrated security=true ";
sqlconnection sconn = new sqlconnection(connsting);
try
{
sconn.open();
}
catch (exception ex)
{
console.writeline("链接错误:" + ex.message);
}
string sqlmessage=null;
sqlmessage = "select * from student";
sqlcommand scmd = new sqlcommand(sqlmessage, sconn);
sqldatareader sdr = null;
try
{
sdr = scmd.executereader();
console.writeline(" 姓名 性别 年龄 ");
while (sdr.read())
{
console.writeline(sdr["name"] +""+ sdr["sex"]+"" + sdr["age"]);
}
sconn.close();
}
catch (exception ex)
{
console.writeline(ex.message);
}
console.readline();
}
}
}
3.运行结果将会显示数据库中的数据
上一篇: asp.net微信开发(永久素材管理)
下一篇: 对java for 循环执行顺序的详解