刚刚入手VB.NET,对于SQL数据库操作遇到些小问题,请知情者帮忙.在线等~~~

来源:百度知道 编辑:UC知道 时间:2024/06/01 04:34:02
Private Con As String = " <连接字符串>"' <连接字符串>可以自动生成
'ConnStr = "Provider=Sqloledb; User ID=sa; Password=123456; Initial Catalog=mytable; Data Source=127.0.0.1;"我把mssql的默认端口改为1434后,使用如下连接出错.ConnStr = "Provider=Sqloledb; User ID=sa; Password=123456; Initial Catalog=mytable; Data Source=127.0.0.1,1434;"

Private connection As SqlClient.SqlConnection
Private command As SqlClient.SqlCommand
Public Function DBopen() As Boolean '打开数据库
Try
connection = New SqlClient.SqlConnection
connection.ConnectionString = Con
connection.Open()
Return True
Catch ex As Exception
MsgBox(ex.ToString)
Return False
End Try
End Function
Public Function DBclose() As Boolean '关闭数据库
Try
connection = New SqlClient.SqlConnection
connection.ConnectionString = Con
connection.Close()

你干嘛把程序发两次阿
访问数据库简单来说,先建立一个数据库SqlClient.SqlConnection 连接,再建立一个数据命令SqlClient.SqlCommand,然后打开连接执行命令得到结果并关闭连接。就这么简单。给你个例子吧。
Public Function SqlAccess()
{
strSqlConn As String = " <连接字符串>"; //连接字符串
strSqlCmd As string = "<sql查询字符串>"; //sql查询字符串
sqlConn As SqlClient.SqlConnection; //申明一个连接
sqlCmd As SqlClient.SqlCommand; //申明一个SqlCommand
Try
sqlConn = New SqlClient.SqlConnection; //建立连接
sqlConn.ConnectionString = strSqlConn;
sqlCmd = New SqlClient.SqlCommand(strSqlCmd ,sqlConn);//建立查询
sqlConn.Open() //打开连接
sqlCmd.ExcuteScalar() //执行查询,并返回结果,这里你可以设一个变量来获取结果,比如 tmp = sqlCmd.ExcuteScalar(),我这里省略了
Catch ex As Exception
MsbBox(ex.ToString) //显示错误信息
Finally
sqlConn.Close() //关闭连接
End Try

}