怎么实现程序与数据库的连接
发布网友
发布时间:2022-04-28 16:02
我来回答
共2个回答
热心网友
时间:2022-04-10 00:07
string sql ="server=192.168.0.59;uid=sa;pwd=panwei;database=master";//连接字符串conn = new SqlConnection(sql);//声明连接对象conn.Open();//连接打开就连上了.net和Java本质上没有区别,都是托管型的。.net是建立在java基础上的,增加了一些新的东西
热心网友
时间:2022-04-10 01:25
#region 创建连接
private SqlConnection objSqlConnection = null;
//private readonly string conStr = ConfigurationManager.AppSettings["conStr"].ToString();
public DBHelper()
{
//objSqlConnection = new SqlConnection(conStr);
objSqlConnection = new SqlConnection("Data Source=.;Initial Catalog=KaWaSystem;Integrated Security=True");
}
#endregion #region 执行insert,update,delete public int ExcuteNonQuery(string sql)
{
SqlCommand objSqlCommand = new SqlCommand(sql, objSqlConnection);
objSqlConnection.Open();
return objSqlCommand.ExecuteNonQuery();
} public int ExcuteNonQuery(string cmdText, SqlParameter[] paras)
{
SqlCommand objSqlCommand = new SqlCommand(cmdText, objSqlConnection);
objSqlConnection.Open();
objSqlCommand.CommandType = CommandType.StoredProcere;
objSqlCommand.Parameters.AddRange(paras);
return objSqlCommand.ExecuteNonQuery(); }
#endregion #region 执行Select语句 public SqlDataReader GetReader(string sql)
{
SqlCommand objSqlCommand = new SqlCommand(sql, objSqlConnection);
objSqlConnection.Open();
return objSqlCommand.ExecuteReader();
} public SqlDataReader GetReader(string cmdText, SqlParameter[] paras)
{
SqlCommand objSqlCommand = new SqlCommand(cmdText, objSqlConnection);
objSqlConnection.Open();
objSqlCommand.CommandType = CommandType.StoredProcere;
if (paras!=null)
{
objSqlCommand.Parameters.AddRange(paras);
}
return objSqlCommand.ExecuteReader();
} #endregion #region 操作DataSet public DataSet GetDataSet(string sql)
{
SqlDataAdapter da = new SqlDataAdapter(sql, objSqlConnection);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
} public DataSet GetDataSet(string cmdText, SqlParameter[] paras)
{
SqlDataAdapter da = new SqlDataAdapter(cmdText, objSqlConnection);
da.SelectCommand.CommandType = CommandType.StoredProcere;
da.SelectCommand.Parameters.AddRange(paras);
DataSet ds = new DataSet();
da.Fill(ds);
return ds; }
#endregion
#region 返回首行首列的值
public object ExecuteScalar(string sql)
{
SqlCommand objSqlCommand = new SqlCommand(sql, objSqlConnection);
objSqlConnection.Open();
return objSqlCommand.ExecuteScalar();
} public object ExecuteScalar(string comText, SqlParameter[] param)
{
SqlCommand objSqlCommand = new SqlCommand(comText, objSqlConnection);
objSqlConnection.Open();
objSqlCommand.CommandType = CommandType.StoredProcere;
objSqlCommand.Parameters.AddRange(param);
return objSqlCommand.ExecuteScalar();
}
#endregion #region 关闭连接
/// <summary>
/// 关闭链接数据库
/// </summary>
public void CloseCon()
{
if (objSqlConnection.State == ConnectionState.Open)
{
objSqlConnection.Close();
}
}
#endregion 这个是一个通用的链接类,但是还要在web。config里面配置才行,然后你就在你的方法里面调用就行了,至于。net和Java之间的区别,你到网上自己找找,里面有很专业的回答。