buddy:下面是对数据库操作的最基本方式- 打开 & 关闭 & 执行Sql
/// 定义数据库对象
private static OleDbConnection conn = new OleDbConnection();
private static OleDbCommand comm = new OleDbCommand();
/// 打开连接
private static void openConnection()
{
if (conn.State == ConnectionState.Closed)
{
try
{
conn.ConnectionString =System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
comm.Connection = conn;
conn.Open();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
/// 关闭连接
private static void closeConnection()
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
comm.Dispose();
}
/// 执行一条sql语句
public static void ExecuteSql(string sqlStr)
{
try
{
openConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlStr;
comm.ExecuteNonQuery();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
}
public SqlConnection objConn;
objConn = new SqlConnection("server=(local);uid=sa;pwd=sa;database=dbBy");//就是这句话读取的配置文件的数据.
SqlCommand strComm = new SqlCommand(strSql, objConn);
SqlDataReader dr = null;
try
{
objConn.Open();
dr = strComm.ExecuteReader();
}
catch
{
}
while (dr.Read())
{
ddlType.Items.Add(new ListItem(dr[1].ToString(),dr[0].ToString()));
}
dr.Close();
objConn.close();
意思是查询公司类型表,得到记录,绑定在UI的dropdownlist控件中
写入新的代码,不进行编译是不行的。你启动执行的时候就是先编译后执行的过程。
建议下载DbSqlHelper.cs 无论学习还是使用都很好。