C#連接數據庫在類方面沒有java通用,不同數據庫有不同的類庫。在這裡只做了SqlServer的連接類。
public class DbLink { private string config = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;//這裡可以直接寫連接字符串 private SqlConnection con; private OracleConnection oracon; private SqlCommand com; private SqlTransaction sqlTra; public DbLink() { con = new SqlConnection(config); con.Open(); com = new SqlCommand(); com.Connection = con; } // 數據檢索 public SqlDataReader select(string sql) { com.CommandText = sql; SqlDataReader sdr = com.ExecuteReader(); return sdr; } // 件數檢索 public int selectCount(string sql) { com.CommandText = sql; int count = (int)com.ExecuteScalar(); return count; } // 數據更新/添加/刪除 public int update(string sql) { com.CommandText = sql; int num = com.ExecuteNonQuery(); return num; } // 開啟事物 public void beginTransaction() { sqlTra = con.BeginTransaction(); com.Transaction = sqlTra; } // 事物提交 public void commit() { sqlTra.Commit(); } // 事物回滾 public void rollback() { sqlTra.Rollback(); } }
連接字符串配置在 web.config 中。
<connectionStrings> <add name="SqlConnection" connectionString="server=.;database=Temp;uid=sa;pwd=123" providerName="System.Data.SqlClient"/> </connectionStrings>