发布网友 发布时间:2022-04-08 00:03
共2个回答
懂视网 时间:2022-04-08 04:25
Webconfig代码
<configuration>
<appSettings>
<add key="myconnect" value="server=.;UID=sa;password=‘1‘;database=test" />
</appSettings>
</configuration>
?
数据库类代码
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
?
/// <summary>
///DB_class 的摘要说明
/// </summary>
public class DB_class
{
SqlConnection myconn;
SqlCommand mycmd;
DataSet ds; //数据集
SqlDataAdapter adapt;
????public DB_class()
????{
????????//
????????//TODO: 在此处添加构造函数逻辑
????????//
????}
public SqlConnection GetConnection()
{
string mystr = ConfigurationManager.AppSettings["myconnect"].ToString();
SqlConnection myconn = new SqlConnection(mystr);
return myconn;
}
?
public int ExecNonQuery(string strSql)
{
?
try
{
myconn = GetConnection();//与数据库连接
mycmd = new SqlCommand();//初始化SqlCommand类对象
mycmd.Connection = myconn;
mycmd.CommandText = strSql;
if (mycmd.Connection.State != ConnectionState.Open)
{
mycmd.Connection.Open();//打开与数据库的连接
}
int a=mycmd.ExecuteNonQuery();//执行Sql操作,并返回受影响的行数
return a;
?
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
?
}
finally
{
if (mycmd.Connection.State == ConnectionState.Open)
{//断开连接,释放资源
mycmd.Connection.Close();
myconn.Dispose();
mycmd.Dispose();
?
}
}
}
?
public string ExecScalar(string strSql)
{
try
{
myconn = GetConnection();//与数据库连接
mycmd = new SqlCommand();//初始化SqlCommand类对象
mycmd.Connection = myconn;
mycmd.CommandText = strSql;
if (mycmd.Connection.State != ConnectionState.Open)
{
mycmd.Connection.Open();//打开与数据库的连接
}
//使用SqlCommand对象的ExecuteScalar方法返回第一行第一列的值
//strSql = Convert.ToString(mycmd.ExecuteScalar());
string another = Convert.ToString(mycmd.ExecuteScalar());
return another;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
?
}
finally
{
if (mycmd.Connection.State == ConnectionState.Open)
{//断开连接,释放资源
myconn.Dispose();
mycmd.Connection.Close();
mycmd.Dispose();
?
}
}
}
?
public DataTable GetDataSet(string strSql, string TableName)
{
ds = new DataSet();
try
{
myconn = GetConnection();//与数据库连接
adapt = new SqlDataAdapter(strSql, myconn); //实例化SqlDataAdapter类对象
adapt.Fill(ds, TableName);//填充数据集
return ds.Tables[TableName];//返回数据集DataSet的表的集合
?
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
?
}
finally
{//断开连接,释放资源
myconn.Close();
adapt.Dispose();
ds.Dispose();
myconn.Dispose();
}
?
}
}
.net/c#连接sqlserver
标签:
热心网友 时间:2022-04-08 01:33
先说.Net:它不是语言,而是微软推出的开发平台,在这个平台上可以使用VB、C#、C++、Java等语言编写程序。