C# VS连接数据库DBhelp
MySql数据库连接
public static string connStr = "Database=AliceDB;Data Source=127.0.0.1;Port=3306;UserId=root;Password=123456;Charset=utf8;TreatTinyAsBoolean=false;Allow User Variables=True";
MySqlHelper的方法:
insert & update
public static bool UpdateOpera(string sql) { MySqlConnection connection = new MySqlConnection(connStr);//实例化链接 connection.Open();//开启连接 MySqlCommand cmd = new MySqlCommand(sql, connection); try { cmd.CommandText = sql; return cmd.ExecuteNonQuery() > 0; } catch (System.Exception ex) { connection.Close(); Console.WriteLine(ex.ToString()); return false; } finally { connection.Close(); } }
Orcl数据库连接
public static string connStr = "User Id=Alice;Password=123456;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=root)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME = orcl)))"
OrclHelper的方法:
select & insert & update
#region 执行查询全部SQL语句,返回DataTable; 查询全部 DataTable dt = OracleHelper.ExecuteDataTable(sqlString); for (int i = 0; i < dt.Rows.Count; i++) { DataRow mydr = dt.Rows[i]; string email = mydr["email"].ToString(); } public static DataTable ExecuteDataTable(string sql, params OracleParameter[] parameters) { OracleConnection connection = new OracleConnection(connStr); OracleCommand cmd = new OracleCommand(sql, connection); try { if (connection.State != ConnectionState.Open) { connection.Open(); } cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); OracleDataAdapter adapter = new OracleDataAdapter(cmd); DataTable datatable = new DataTable(); adapter.Fill(datatable); return datatable; } catch (System.Exception ex) { connection.Close(); //Console.WriteLine(ex.ToString()); return null; } finally { connection.Close(); } } #endregion #region执行插入或修改SQL语句,返回True & false; if (OracleHelper.UpdateOpera(updateStr)) { MessageBox.Show("成功") } public static bool UpdateOpera(string sql, params OracleParameter[] parameters) { OracleConnection connection = new OracleConnection(connStr); OracleCommand cmd = new OracleCommand(sql, connection); try { if (connection.State != ConnectionState.Open) { connection.Open(); } cmd.CommandText = sql; return cmd.ExecuteNonQuery() > 0; } catch (System.Exception ex) { connection.Close(); //Console.WriteLine(ex.ToString()); return false; } finally { connection.Close(); } } #endregion #region执行查询SQL语句,返回是否存在; OracleDataReader reader = OracleHelper.ExecuteReader(sqlCount); while (reader.Read()) { //存在去修改 } public static OracleDataReader ExecuteReader(string strSQL, params OracleParameter[] parameters) { connection = new OracleConnection(connStr); OracleCommand cmd = new OracleCommand(strSQL, connection); try { if (connection.State != ConnectionState.Open) { connection.Open(); } OracleDataReader myReader = cmd.ExecuteReader(); return myReader; } catch (OracleException e) { connection.Close(); throw new Exception(e.Message); } //finally //{ // connection.Close(); //} } #endregion
Sqlserver数据库连接