写入数据库的具体步骤:
1、首先新建一个项目。
2、建立一个数据库连接类LinkDataBase。因为数据库操作有很多都是重复性工作,所以写一个类来简化对数据库的操作。
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace Test
...{
class LinkDataBase
...{
//设置连接字符串
private string strSQL;
//与数据库连接
private string connectionString = "Data Source=Localhost;Initial Catalog=Test;Integrated Security=True";
private SqlConnection myConnection;
private SqlCommandBuilder sqlCmdBld;
private DataSet ds = new DataSet();
private SqlDataAdapter da;
public LinkDataBase()
...{
}
//根据输入的SQL语句检索数据库数据
public DataSet SelectDataBase(string tempStrSQL, string tempTableName)
...{
this.strSQL = tempStrSQL;
this.myConnection = new SqlConnection(connectionString);
this.da = new SqlDataAdapter(this.strSQL, this.myConnection);
this.ds.Clear();
this.da.Fill(ds, tempStrSQL);
//返回填充了数据的DataSet,其中数据表以tempTableName给出的字符串命名
return ds;
}
//数据库数据更新(传DataSet和DataTable的对象)
public DataSet UpdateDataBase(DataSet changedDataSet, string tableName)
...{
this.myConnection = new SqlConnection(connectionString);
this.da = new SqlDataAdapter(this.strSQL, this.myConnection);
this.sqlCmdBld = new SqlCommandBuilder(da);
this.da.Update(changedDataSet, tableName);
//返回更新过的数据库表
return changedDataSet;
}
//检索数据库数据(传字符串,直接操作数据库)
public DataTable SelectDataBase(string tempStrSQL)
...{
this.myConnection = new SqlConnection(connectionString);
DataSet tempDataSet = new DataSet();
this.da = new SqlDataAdapter(tempStrSQL, this.myConnection);
this.da.Fill(tempDataSet);
return tempDataSet.Tables[0];
}
//数据库数据更新(传字符串,直接操作数据库)
public int UpdateDataBase(string tempStrSQL)
...{
this.myConnection = new SqlConnection(connectionString);
myConnection.Open();
SqlCommand tempSqlcommand = new SqlCommand(tempStrSQL, this.myConnection);
int intNumber = tempSqlcommand.ExecuteNonQuery();
myConnection.Close();
return intNumber;
}
}
}