Posted in 面试题 onApril 16, 2013
用C#语言写出与SQLSERVER访问时的具体过程。在涉及到SQLSERVER数据库编程的时候要注意哪些方面?
答: private SqlConnection conn;//定义一个数据库连接
private SqlCommand com;//定义执行命令
public data()
{
//在配置文件中设置
conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.AppSettings["connString"].ToString();
}
//打开数据库
public void open()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
//关闭数据库
public void close()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
//执行数据库操作,返回DataSet
public void getDataSet(string proc,SqlParameter[] parm,out DataSet ds)
{
com = getCommand(proc,parm);
SqlDataAdapter sda = new SqlDataAdapter(com);
ds = new DataSet();
sda.Fill(ds);
}
//返回SqlCommadn
public SqlCommand getCommand(string proc, SqlParameter[] parm)
{
SqlCommand com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = proc;
foreach (SqlParameter p in parm)
{
com.Parameters.Add(p);
}
return com;
}
//返回DataReader
public SqlDataReader getDataReader(string proc, SqlParameter[] parm)
{
com = getCommand(proc, parm);
return com.ExecuteReader();
}
//执行数据库操作,返回void
public void ExecuteCommand(string proc, SqlParameter[] parm)
{
com = getCommand(proc, parm);
open();
com.ExecuteNonQuery();
close();
}
注意:引用 using System.Data.SqlClient,如果是连接模式记得完了后断开连接,SqlDataReader记得关闭,出错了怎么处理
答: private SqlConnection conn;//定义一个数据库连接
private SqlCommand com;//定义执行命令
public data()
{
//在配置文件中设置
conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.AppSettings["connString"].ToString();
}
//打开数据库
public void open()
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
}
//关闭数据库
public void close()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
//执行数据库操作,返回DataSet
public void getDataSet(string proc,SqlParameter[] parm,out DataSet ds)
{
com = getCommand(proc,parm);
SqlDataAdapter sda = new SqlDataAdapter(com);
ds = new DataSet();
sda.Fill(ds);
}
//返回SqlCommadn
public SqlCommand getCommand(string proc, SqlParameter[] parm)
{
SqlCommand com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = proc;
foreach (SqlParameter p in parm)
{
com.Parameters.Add(p);
}
return com;
}
//返回DataReader
public SqlDataReader getDataReader(string proc, SqlParameter[] parm)
{
com = getCommand(proc, parm);
return com.ExecuteReader();
}
//执行数据库操作,返回void
public void ExecuteCommand(string proc, SqlParameter[] parm)
{
com = getCommand(proc, parm);
open();
com.ExecuteNonQuery();
close();
}
注意:引用 using System.Data.SqlClient,如果是连接模式记得完了后断开连接,SqlDataReader记得关闭,出错了怎么处理
用C#语言写出与SQLSERVER访问时的具体过程
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Tags in this post...
Reply on: @reply_date@
@reply_contents@