VS2008如何连接数据库SQLserver2008

2024-12-01 07:12:28
推荐回答(5个)
回答1:

在webconfig下写



然后写一个类,这里起名叫DataBase
public class DataBase
{
private string connectionString = "";

public DataBase()
{
//
// TODO: 在此处添加构造函数逻辑
//

connectionString = ConfigurationManager.ConnectionStrings["DataConnectionString"].ToString();
}
//设置链接属性
public string conStr
{
get { return connectionString; }
}
//测试链接数据库
public string testCon()
{
string temCon = conStr;
string conEx = "";
SqlConnection con = new SqlConnection(temCon);
try
{
con.Open();
con.Close();
}
catch (Exception ex)
{
conEx = ex.Message;
}
finally
{
}
return conEx;
}

}
然后每次用的时候:
DataBase db=new DataBase();
SqlConnnection conn=new Sqlconnection();
conn.ConnectionString=db.conStr;
conn.Open();

回答2:

1.建工程选择WEB--->ASP.NET WEB 应用程序.
2.建议下一个SQLHelper.cs类,简化数据库的调用.
给你一个使用SQLHELPER调用数据库的示例:
///


/// 提取站点基本信息
///

///
///
///
public bool LoadEntityName(string EntityID, out DataSet ds)
{
bool ret = false;
ds = null;
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM Entity WHERE EntityID=@EntityID ");
SqlParameter[] parameter = new SqlParameter[1];
parameter[0] = new SqlParameter("@EntityID", EntityID);
using (SqlConnection conn = new SqlConnection(Gloabal.G_CONN))
{
try
{
ds = SqlHelper.ExecuteDataset(Gloabal.G_CONN, CommandType.Text, strSql.ToString(), parameter);
ret = true;
}
catch (Exception)
{
ret = false;
}
}
return ret;
}
//Gloabal.G_CONN表示数据库联接字符串格式:Data Source=.;Initial Catalog=数据库名;User ID=sa;Password=123;Connect Timeout=0;pooling = true; connection lifetime = 0;

回答3:

Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim oleCon As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=E:/phoneNumber.mdb")
Dim oleCmd As OleDbCommand
Dim oleDs As New DataSet
Dim oleApt As OleDbDataAdapter
Dim oleRd As OleDbDataReader

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
oleCon.Open()
MsgBox("连接成功")
oleCmd = New OleDbCommand()
oleCmd.Connection = oleCon
oleCmd.CommandText = "select phone_start from tb_phonenum"
oleRd = oleCmd.ExecuteReader
Do While oleRd.Read
ListBox1.Items.Add(oleRd(0))
Loop
oleRd.Close()
Catch ex As Exception
MsgBox(e.ToString, 0)
Finally
oleCon.Close()
End Try
End Sub
希望对你有帮助

回答4:

SqlConnection mycon = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=xxgl;Integrated Security=True");

回答5:

web不会,我可以帮你顶!