在c#中数据库的操作主要是由ado.net完成,这个概念和java的jdbc类似,使用ado.net可以连接任意一种数据库,也就是说ado.net为数据库操作提供了统一接口。掌握了这门技术就可以操作任何的数据库了。这里呢就使用vstudio里内置的数据库。、
1.连接数据库(sqlserver2005)的代码
string path = AppDomain.CurrentDomain.BaseDirectory;
if (path.EndsWith(@"\bin\Debug") || path.EndsWith(@"\bin\Release"))
{
path = System.IO.Directory.GetParent(path).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory",path);
}
2.打开数据库连接
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\mydb.mdf;Integrated Security=True;User Instance=True")
mydb.mdf是数据库文件的名称
3.进行数据的增删改查
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace database
{
class Program
{
static void Main(string[] args)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
if (path.EndsWith(@"\bin\Debug") || path.EndsWith(@"\bin\Release"))
{
path = System.IO.Directory.GetParent(path).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory",path);
}
//开始测试数据库连接
try {
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\mydb.mdf;Integrated Security=True;User Instance=True")) {
conn.Open();
//向数据库插入数据
using (SqlCommand command =conn.CreateCommand()) {
string name = "will";
string password = "123456";
/*command.CommandText="insert into customer(name,password) values('" +name+ "','"+ password +"')";
//command.CommandText = "insert into customer(name,password) values('tom','123')";
int temp=command.ExecuteNonQuery();
if(temp==1){
Console.WriteLine("数据保存成功");
}*/
command.CommandText="select * from customer";
using(SqlDataReader reader=command.ExecuteReader()){
while (reader.Read())
{
string fname = reader.GetString(1);
string fpassword = reader.GetString(reader.GetOrdinal("password"));
Console.WriteLine(fname + "," + fpassword);
}
}
}
}
}catch(Exception e){
Console.WriteLine(e.StackTrace);
}
Console.ReadKey();
}
}
}
程序里的using(){}可以不使用,使用了的好处就是程序会替我们关闭数据库连接,这里即使调用了close方法数据库连接其实并没有真正关闭,这里程序实际上先调用了dispose方法,在这个方法里再调用close方法。最值得关注的就是要引入名称空间System.Data.SqlClient
其他的操作我就不写出来了,大家自己写写吧。