vb数据库连接字符串

合集下载

VBA编程中的数据库连接与操作详解

VBA编程中的数据库连接与操作详解

VBA编程中的数据库连接与操作详解VBA(Visual Basic for Applications)是一种用于编写Microsoft Office 应用程序的编程语言。

在VBA编程中,与数据库的连接和操作是非常重要的一部分。

本文将详细介绍VBA编程中的数据库连接和操作,并提供一些实例来帮助读者更好地理解。

一、数据库连接1. 连接字符串数据库连接通常需要使用连接字符串来指定数据库的位置和其他连接参数。

连接字符串的格式取决于所使用的数据库类型。

下面是一些常见数据库的连接字符串示例:- Access数据库:Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myDatabase.accdb;Persist SecurityInfo=False;- SQL Server数据库:Provider=SQLOLEDB;DataSource=serverName;Initial Catalog=databaseName;UserID=userName;Password=password;- MySQL数据库:Driver={MySQL ODBC 5.3Driver};Server=serverAddress;Database=databaseName;User=user ;Password=password;Option=3;需要注意,以上示例中的连接字符串仅供参考,实际使用时应根据具体情况进行修改。

2. 打开连接在VBA中,可以使用ADODB(ActiveX Data Objects)对象来进行数据库操作。

首先需要创建一个ADODB.Connection 对象,并使用连接字符串来打开连接。

下面是一个示例:```vbaDim conn As ObjectSet conn = CreateObject("ADODB.Connection")conn.ConnectionString ="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\myFolder\myDatabase.accdb;Persist SecurityInfo=False;"conn.Open```在打开连接之前,可以根据需要设置连接对象的其他属性,如CommandTimeout(执行命令的超时时间)和CursorLocation(指定游标的位置)等。

VBA中的字符串连接与分割方法详解

VBA中的字符串连接与分割方法详解

VBA中的字符串连接与分割方法详解在VBA(Visual Basic for Applications)编程中,字符串处理是常见的操作之一。

字符串连接和分割是两个常用的字符串处理方法,它们在处理文本数据、字符串操作以及表格处理等方面发挥着重要的作用。

在本文中,我们将详细介绍VBA中的字符串连接和分割方法,以帮助读者更好地理解和应用这些方法。

一、字符串连接方法字符串连接方法是将多个字符串合并成一个字符串的过程。

在VBA中,有多种方法可以实现字符串连接,下面我们将逐一介绍这些方法。

1. 使用&符号在VBA中,可以使用&符号将两个字符串连接起来。

例如,以下示例将字符串"Hello, "和"World!"连接起来,并将结果输出到MsgBox 中:```vbaDim str1 As StringDim str2 As StringDim result As Stringstr1 = "Hello, "str2 = "World!"result = str1 & str2MsgBox result```运行以上代码,将会在消息框中显示"Hello, World!"。

2. 使用"+"符号类似于使用&符号进行字符串连接,我们还可以使用"+"符号来连接两个字符串。

以下示例展示了利用"+"符号连接字符串的方法:```vbaDim str1 As StringDim str2 As StringDim result As Stringstr1 = "Hello, "str2 = "World!"result = str1 + str2MsgBox result```运行以上代码,将会在消息框中显示"Hello, World!"。

VB中数据库的连接方法

VB中数据库的连接方法

VB中数据库的连接方法目前,绝大多数的数据库参考书都介绍了ODBC的手工配置方法,或者介绍了如何在代码中进行ODBC配置。

但这两种方法都有一定的局限性:不是当程序最终完成并分发到用户手中后,还需要为用户配置ODBC,显得既麻烦又不符合专业软件的要求;就是得编写复杂的更改操作系统注册表文件的程序,十分烦琐。

本文从ADO(ActiveX Data Objects)入手,介绍无需配置数据源的几种常用大型数据库连接方法。

本文所述的无“数据源”连接,意义不是不需要数据源,否则连接无从谈起,而是不需要配置注册数据源所进行的连接。

ODBC(Open DataBase Connectivity,开放式数据库连接)是用于连接不同数据源的标准编程语言接口。

许多文章中介绍,在实现ODBC时,必须首先配置ODBC环境,进行数据源的注册,然后才能在对数据库编程时,对数据源进行连接、访问和操作,并提供了用PB或VB等语言工具实现数据源注册的具体方法。

这些方法不但复杂烦琐,而且由于参数内容不一,配置时令人感觉无所适从,不宜把握。

走近ADOADO是微软提供的数据库访问技术。

它被设计用来同新的数据访问层OLE DB Provider 一起协同工作,以提供通用数据访问(Universal Data Access)能力。

OLE DB是一个底层的数据访问接口,用它可以访问各种数据源,包括传统的关系型数据库、电子邮件系统及自定义的商业对象等。

ADO提供了一个熟悉的、高层的对OLE DB的Automation封装接口。

对那些熟悉RDO的程序员来说,可以把OLE DB看作ODBC驱动程序,如同RDO对象是ODBC驱动程序接口一样,ADO对象是OLE DB的接口。

同样,像不同的数据库系统需要它们自己的ODBC驱动程序一样,不同的数据源也要求它们自己的OLE DB提供者(OLE DB provider)。

目前,虽然OLE DB提供者比较少,但微软正积极推广该技术,并计划用OLE DB取代ODBC。

vb.net数据库连接池的连接字符串写法

vb.net数据库连接池的连接字符串写法

数据库连接池的连接字符串写法在 中,连接字符串是用来建立与数据库之间的连接的关键元素。

连接字符串的写法取决于你使用的数据库类型和数据库引擎。

以下是一个示例连接字符串,用于连接到Microsoft SQL Server 数据库的连接池:```Imports System.Data.SqlClientModule Module1Sub Main()Dim connectionString As String = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword;Integrated Security=False;Max Pool Size=100;Pooling=True;"Dim connection As New SqlConnection(connectionString)Tryconnection.Open()' 连接已经打开,可以执行数据库操作Console.WriteLine("Connected to SQL Server")Catch ex As ExceptionConsole.WriteLine("Error: " & ex.Message)Finallyconnection.Close()End TryEnd SubEnd Module```在这个示例中,你需要替换`YourServerName`、`YourDatabaseName`、`YourUsername` 和`YourPassword` 分别为你的SQL Server 的实际信息。

`Max Pool Size` 和`Pooling` 是用于配置连接池的选项,它们指定了连接池的最大大小和是否启用连接池。

VB与数据库连接的几种方法

VB与数据库连接的几种方法

VB与数据库连接的几种方法在VB中,有多种方法可以连接数据库。

以下是几种常见的方法:1. 使用OLE DB连接:OLE DB是Microsoft提供的一种连接数据库的标准接口,可以连接各种类型的数据库。

可以通过VB中的ADO(ActiveX Data Objects)对象来使用OLE DB连接数据库。

以下是一个使用OLE DB连接数据库的示例代码:```Dim conn As New ADODB.Connectionconn.ConnectionString = "Provider=SQLOLEDB;DataSource=ServerName;Initial Catalog=DatabaseName;UserID=Username;Password=Password"conn.Open```上述代码中,通过设置ConnectionString属性来指定数据库连接字符串,其中包含了数据库类型、服务器名称、数据库名称、用户名和密码等信息。

然后调用Open方法打开数据库连接。

2. 使用ODBC连接:ODBC(Open Database Connectivity)也是一种标准的数据库连接接口,可以连接多种类型的数据库。

可以通过VB中的ODBC对象来使用ODBC连接数据库。

以下是一个使用ODBC连接数据库的示例代码:```Dim conn As New ADODB.Connectionconn.ConnectionString = "Driver={SQL Server Native Client 11.0};Server=ServerName;Database=DatabaseName;Uid=Username;Pwd=P assword;"conn.Open```上述代码中,通过设置ConnectionString属性来指定ODBC连接字符串,其中包含了ODBC驱动程序名称、服务器名称、数据库名称、用户名和密码等信息。

vb odbc语法

vb odbc语法

vb odbc语法在VB中,ODBC(开放式数据库连结,Open Database Connectivity)被用于访问各种数据库,如SQL Server、MySQL、Oracle等。

ODBC提供了一种标准的接口,使得程序可以无需考虑具体的数据库类型而进行数据库操作。

本文将介绍VB中使用ODBC语法进行数据库操作的方法。

1. 连接数据库在VB中使用ODBC连接数据库,需要使用`ADODB.Connection`对象。

首先,需要引入`ADODB`的引用。

在VB的代码编辑器中,点击"项目"->"引用",然后勾选"Microsoft ActiveX Data Objects x.x Library"。

接下来,在代码中声明一个`ADODB.Connection`对象,并设置连接字符串和提供程序。

```vbDim conn As New ADODB.Connectionconn.ConnectionString = "DRIVER={SQL Server Native Client 11.0};SERVER=127.0.0.1; DATABASE=MyDatabase; UID=sa; PWD=123456;"conn.Provider = "MSDASQL"conn.Open```上述代码中,连接字符串设置了数据库的驱动程序、服务器地址、数据库名称、用户名和密码。

这里以SQL Server为例,驱动程序为"SQL Server Native Client11.0",服务器地址为"127.0.0.1",数据库名称为"MyDatabase",用户名为"sa",密码为"123456"。

2. 查询数据连接数据库后,可以使用`ADODB.Recordset`对象进行查询操作。

VBA中数据库操作与连接的实现方法

VBA中数据库操作与连接的实现方法

VBA中数据库操作与连接的实现方法在VBA编程中,数据库操作与连接是非常重要的一部分。

使用VBA可以连接各种数据库,如Access、SQL Server、Oracle等,并对数据库进行各种操作,如查询、插入、更新和删除数据。

本文将介绍VBA中实现数据库操作与连接的方法。

一、连接数据库在VBA中连接数据库常用的方法是使用ADO (ActiveX Data Objects)来建立与数据库的连接。

ADO是一套由微软提供的用于操纵各种数据源的组件。

下面是一个简单的连接Access数据库的示例:```vbaDim conn As New ADODB.ConnectionDim strConn As StringstrConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\路径\数据库文件.accdb"conn.Open strConn```上述代码中,我们首先声明了一个ADODB.Connection 类型的变量conn,并创建了一个字符串变量strConn,用于存储连接字符串。

然后,我们通过conn.Open方法打开数据库连接,传入连接字符串作为参数。

连接字符串中的Provider表示数据库的提供者,这里使用了Access数据库的提供者。

Data Source表示数据库的文件路径,根据实际情况进行修改即可。

除了Access数据库,如果是连接SQL Server数据库,连接字符串可以类似如下:```vbastrConn = "Provider=SQLOLEDB;Data Source=服务器地址;Initial Catalog=数据库名称;User ID=用户名;Password=密码"```需要根据实际情况修改服务器地址、数据库名称、用户名和密码。

二、执行SQL语句连接数据库成功后,我们可以通过执行SQL语句来对数据库进行操作。

vb字符串运算符

vb字符串运算符

vb字符串运算符VB字符串运算符在VB编程中,字符串是一种非常重要的数据类型。

字符串运算符是用于对字符串进行操作和处理的特殊符号。

本文将介绍一些常用的VB字符串运算符,并对其功能和使用进行详细说明。

1. 连接运算符(&)连接运算符(&)用于将两个字符串连接在一起,形成一个新的字符串。

例如:```vbDim str1 As String = "Hello"Dim str2 As String = "World"Dim result As String = str1 & str2```上述代码中,result的值将为"HelloWorld"。

连接运算符可以用于连接任意数量的字符串,不局限于两个。

例如:```vbDim str1 As String = "Hello"Dim str2 As String = " "Dim str3 As String = "World"Dim result As String = str1 & str2 & str3```上述代码中,result的值将为"Hello World"。

2. 比较运算符(=、<>)比较运算符(=、<>)用于比较两个字符串的值是否相等。

例如:```vbDim str1 As String = "Hello"Dim str2 As String = "World"Dim isEqual As Boolean = (str1 = str2)```上述代码中,isEqual的值将为False,因为str1和str2的值不相等。

如果要判断两个字符串的值是否不相等,可以使用<>运算符。

例如:```vbDim str1 As String = "Hello"Dim str2 As String = "World"Dim isNotEqual As Boolean = (str1 <> str2)```上述代码中,isNotEqual的值将为True,因为str1和str2的值不相等。

数据库连接-连接字符串

数据库连接-连接字符串

一.数据库的连接字符串string connectionstr = "Data Source=PC201305072142\\SQLEXPRESS;Da taBase=db_stu;User ID=sa;pwd=123456";Data Source后加你的连接服务器,DataBase后加连接的数据库ID=sa;pwd=123456ID:用户名Pwd:密码二.C#语言实现SQL SERVER、access连接SQL SERVER:添加 using System.Data.SqlClient;SqlConnection con =new SqlConnection("server=.;database=数据库名;uid=sa;pwd=密码");//密码是你数据库sa的登录的密码或者是 SqlConnection con = new SqlConnection("Data source=你的数据库服务器;Initial Catalog=要连接的数据库名;trusetd_connection=sspi");//c是window身份认证的方式access:添加using System.Data.OleDb;OleDbConnection omd=newOleDbConnection("Provider=Microsoft.jet.oldb.4.0;database=数据库的相对路径");//路径是想对你程序运行的路径三.问:如何手动设置数据库连接(数据库的IP、登录密码、用户名称以让用户自己输入一次,然后把它们保存到配置文件中,以后就不需要再输了,直接从配置文件中读取就行了)答:1、在解决方案中添加一个新的类,命名CL_Conn,用于连接数据库。

完整代码如下:using System;using System.Collections.Generic;using ponentModel;using System.Text;using System.Windows.Forms;using Microsoft.Data.ConnectionUI;namespace CL_Conn{public class Conn{/// <summary>/// 获取 自带的数据库连接对话框的数据库连接信息/// </summary>/// <returns>数据库连接</returns>public string GetDatabaseConnectionString(){string connString = String.Empty;Microsoft.Data.ConnectionUI.DataConnectionDialog connDialog = new Microsoft.Data.ConnectionUI.DataConnectionDialog();// 添加数据源列表,可以向窗口中添加自己程序所需要的数据源类型必须增加以下几项中任一一项connDialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.AccessDataSo urce); // AccessconnDialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.OdbcDataSou rce); // ODBCconnDialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.OracleDataSo urce); // OracleconnDialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.SqlDataSourc e); // Sql ServerconnDialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.SqlFileDataSo urce); // Sql Server File// 初始化connDialog.SelectedDataSource =Microsoft.Data.ConnectionUI.DataSource.SqlDataSource;connDialog.SelectedDataProvider =Microsoft.Data.ConnectionUI.DataProvider.SqlDataProvider;//只能够通过DataConnectionDialog类的静态方法Show出对话框//不同使用dialog.Show()或dialog.ShowDialog()来呈现对话框if(Microsoft.Data.ConnectionUI.DataConnectionDialog.Show(connDialog) == DialogResult.OK){connString = connDialog.ConnectionString;}return connString;}}}2、编译。

string在vb中的用法

string在vb中的用法

string在vb中的用法在VB中,string是一个数据类型,用来表示文本字符串。

以下是一些常见的string的用法:1. 变量声明和初始化:vbDim myString As StringmyString = "Hello, World!"2. 字符串连接:vbDim firstName As String = "John"Dim lastName As String = "Doe"Dim fullName As String = firstName & " " & lastName'' fullName = "John Doe"3. 字符串长度:vbDim myString As String = "Hello, World!"Dim length As Integer = myString.Length'' length = 134. 字符串截取:vbDim myString As String = "Hello, World!"Dim subString As String = myString.Substring(7, 5)'' subString = "World"5. 字符串替换:vbDim myString As String = "Hello, World!"Dim newString As String = myString.Replace("World", "John") '' newString = "Hello, John!"6. 字符串比较:vbDim string1 As String = "Hello"Dim string2 As String = "World"Dim isEqual As Boolean = String.Equals(string1, string2)'' isEqual = False以上是一些常见的string用法,还有其他一些字符串处理函数和方法可以根据需要使用。

vb与数据库的几种连接方法

vb与数据库的几种连接方法

-、用DAO控件连接数据库1.与Access2000数据库连接Private Sub Command1_Click()'也可直接在控件属性中设置以下各项但在控件属性中不能写入密码'只有在数据数没有密码的情况下可以省略Data1.RefreshData1.Connect = "Access 2000;"Data1.DatabaseName = App. Path + "/chncmadb.mdb"'数据库没有密码此句可省Data1.Connect = ";pwd=123456"'Data1.RecordSource = "耕地资源管理单元属性数据表2004"Data1.RecordSource = "select * from 耕地资源管理单元属性数据表2004" Data1.Refresh’move后才能正确显示记录个数End Sub2.与没有密码的DBF文件数据库连接Private Sub Command2_Click()Data1.Connect = "dBASE III;"Data1.DatabaseName = App. Path' Data1.RecordSource ="DBF"Data1.RecordSource = "select * from dbf"Data1.Refresh’move后才能正确显示记录个数End Sub3.与没有密码的Excel文件数据库连接Private Sub Command3_Click()Data1.Connect = "Excel 8.0;"Data1.DatabaseName = App.Path & "/EXcel.xls"Data1.RecordSource = "select * from [EXcel.xls]"Data1.Refresh’move后才能正确显示记录个End Sub二、用DAO代码连接数据库'在使用DAO对象前应选定Visual Basic菜单下的[工程]中的引用了菜单中的[Microsoft DAO 3.6 Object Library]选项,或其它版本1.DAO代码与Access数据库连接Private Sub Command1_Click()Dim Db As DatabaseDim Rs As Recordset'以共享、读写方式打开'如果无密码最后一个参数可以不要Set Db= OpenDatabase(App.Path & "/chncmadb.mdb", False, False, ";pwd=123456")'不需要move来更新记录个数'Set Rs = Db.OpenRecordset("耕地资源管理单元属性数据表2004")'需要move来更新记录个数Set Rs = Db.OpenRecordset("select * from [耕地资源管理单元属性数据表2004]")If Rs.RecordCount > 0 ThenRs.MoveLastRs.MoveFirstEnd IfEnd Sub2.DAO代码与没有密码的DBF文件数据库连接Private Sub Command2_Click()Dim Db As DatabaseDim Rs As Recordset'以共享、读写方式打开Set Db = OpenDatabase(App.Path, False, False, "dbase III;")'不需要move来更新记录个数'Set Rs = Db.OpenRecordset("DBF")’需要move来更新记录个数Set Rs = Db.OpenRecordset("select * from [DBF]")If Rs.RecordCount > 0 ThenRs.MoveLastRs.MoveFirstEnd IfEnd sub3. 'DAO代码与没有密码的Excel文件数据库连接Private Sub Command3_Click()Dim Db As DatabaseDim Rs As Recordset'以共享、读写方式打开'如果无密码最后一个参数可以不要Set Db = OpenDatabase(App.Path & "/EXcel.xls", False, False, "Excel 8.0;") '不需要move来更新记录个数' Set Rs = Db.OpenRecordset("EXcel.xls") '表格中的工作目录sheet'需要move来更新记录个数Set Rs = Db.OpenRecordset("select * from [EXcel.xls]") '表格中的工作目录sheet'If Rs.RecordCount > 0 ThenRs.MoveLastRs.MoveFirstEnd IfEnd Sub三、用ADO控件连接数据库'也可直接在控件属性中设置以下各项1.ADO控件与Access2000数据库连接Private Sub Command1_Click()'连接有密码的Access数据库'Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "/chncmadb1.mdb;Jet OLEDB:DataBase PASSWORD=123456"'连接没有密码的Access数据库Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "/chncmadb.mdb;Persist Security Info=False"'Adodc1.RecordSource = "[耕地资源管理单元属性数据表2004]"Adodc1.RecordSource = "select * from [耕地资源管理单元属性数据表2004]"Adodc1.RefreshSet DataGrid1.DataSource = Adodc1DataGrid1.RefreshEnd Sub2.'ADO控件与DBF表连接Private Sub Command2_Click()'Adodc1.ConnectionString = "Provider=MSDASQL.1;Persist Security Info=False;Data Source=dBASE Files;DBQ=" & App.Path & ";SourceType=DBF;"'Adodc1.ConnectionString = "Provider=MSDASQL.1;Persist Security Info=False;ExtendedProperties=DSN=Visual FoxPro Tables;UID=;SourceDB=”& app.path&”;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"'Adodc1.ConnectionString = "Provider=MSDASQL.1;Persist Security Info=False;ExtendedProperties=DSN=dBASE Files;DBQ=”& app.path &”;;DefaultDir=”& app.path&”;DriverId=533;MaxBufferSize=2048;PageTimeout=5;"'能使表名长度不受限制Adodc1.ConnectionString = "Provider=MSDASQL.1;Driver=Microsoft Visual Foxpro Driver;SourceDB=" & App.Path & ";SourceType=DBF;Locale Identifier=2052"'Adodc1.RecordSource = "[DBF1]"Adodc1.RecordSource = "select * from DBF1"Adodc1.RefreshSet DataGrid1.DataSource = Adodc1DataGrid1.RefreshEnd Sub3.'ADO控件与Excel表连接Private Sub Command3_Click()'下面一句测试未能通过'Adodc1.ConnectionString = "Data Provider=MSDASQL.1;driver=Microsoft Excel Driver *.xls);DBQ=" & App.Path & "/EXcel.xls"'Adodc1.ConnectionString="Provider=MSDASQL.1;Persist Security Info=False;ExtendedProperties=DSN=Excel Files;DBQ=" & App.Path & "/EXcel.xls;DefaultDir=”&app.path&”;DriverId=790;MaxBufferSize=2048;PageTimeout=5;"Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & App.Path & "/EXcel.xls;Extended Properties='Excel 8.0;HDR=Yes'"'Adodc1.RecordSource = "[EXcel.xls]"Adodc1.RecordSource = "select * from [EXcel.xls]"Adodc1.RefreshSet DataGrid1.DataSource = Adodc1DataGrid1.RefreshEnd Sub4.'ADO控件与Oracle数据库连接Private Sub Command4_Click()'Adodc1.ConnectionString = "Provider=MSDAORA.1;Password=chncmadb;User ID=chncmadb;Data Source=towebserver;Persist Security Info=True"Adodc1.ConnectionString="Provider=OraOLEDB.Oracle.1;Password=chncmadb;Persist Security Info=True;User ID=chncmadb;Data Source=towebserver"'Adodc1.RecordSource = "T320481TR012004"'表名不能加方括号Adodc1.RecordSource = "select * from T320481TR012004"Adodc1.RefreshSet DataGrid1.DataSource = Adodc1DataGrid1.RefreshEnd Sub5.'ADO控件与SQLserver数据库连接'未测试Private Sub Command5_Click()Adodc1.ConnectionString = "Provider=SQLOLEDB.1;Password=111;Persist Security Info=True;User ID=111;Initial Catalog=111;Data Source=111"'Adodc1.RecordSource = "T320481TR012004"Adodc1.RecordSource = "select * from T320481TR012004"Adodc1.RefreshSet DataGrid1.DataSource = Adodc1DataGrid1.RefreshEnd Sub四、用ADO代码连接数据库'在使用ADO对象前应选定Visual Basic菜单下的[工程]中的引用了菜单中的[Microsoft.ActiveX Data Object 2.5 Library]选项,或其它版本1.'ADO代码与Access2000数据库连接Private Sub Command1_Click()Dim AdoCnn As ADODB.ConnectionDim AdoRs As ADODB.RecordsetSet AdoCnn = New ADODB.ConnectionSet AdoRs = New ADODB.RecordsetAdoCnn.CursorLocation = adUseClient'.open后面的字符串可以参考ADO控件连接.ConnectionString后面的的字符串AdoCnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "/chncmadb1.mdb;Jet OLEDB:DataBase PASSWORD=123456"AdoRs.Open "select * from [耕地资源管理单元属性数据表2004]", AdoCnn, adOpenDynamic, adLockPessimistic, adCmdTextSet DataGrid1.DataSource = AdoRsSet AdoRs = NothingSet AdoCnn = NothingEnd Sub2.'ADO代码与DBF表连接Private Sub Command2_Click()Dim AdoCnn As ADODB.ConnectionDim AdoRs As ADODB.RecordsetSet AdoCnn = New ADODB.ConnectionSet AdoRs = New ADODB.RecordsetAdoCnn.CursorLocation = adUseClient'.open后面的字符串可以参考ADO控件连接.ConnectionString后面的的字符串AdoCnn.Open "Provider=MSDASQL.1;Driver=Microsoft Visual Foxpro Driver;SourceDB=" & App.Path & ";SourceType=DBF;Locale Identifier=2052"AdoRs.Open "select * from [DBF1]", AdoCnn, adOpenDynamic, adLockPessimistic, adCmdTextSet DataGrid1.DataSource = AdoRsSet AdoRs = NothingSet AdoCnn = NothingEnd Sub3.'ADO代码与Excel表连接Private Sub Command3_Click()Dim AdoCnn As ADODB.ConnectionDim AdoRs As ADODB.RecordsetSet AdoCnn = New ADODB.ConnectionSet AdoRs = New ADODB.RecordsetAdoCnn.CursorLocation = adUseClient'.open后面的字符串可以参考ADO控件连接.ConnectionString后面的的字符串AdoCnn.Open"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" &App.Path & "/EXcel.xls;Extended Properties='Excel 8.0;HDR=Yes'"AdoRs.Open "select * from [EXcel.xls]", AdoCnn, adOpenDynamic, adLockPessimistic, adCmdTextSet DataGrid1.DataSource = AdoRsSet AdoRs = NothingSet AdoCnn = NothingEnd Sub4.'ADO代码与Oracle数据库连接Private Sub Command4_Click()Dim AdoCnn As ADODB.ConnectionDim AdoRs As ADODB.RecordsetSet AdoCnn = New ADODB.ConnectionSet AdoRs = New ADODB.RecordsetAdoCnn.CursorLocation = adUseClient'.open后面的字符串可以参考ADO控件连接.ConnectionString后面的的字符串AdoCnn.Open "Provider=OraOLEDB.Oracle.1;Password=chncmadb;Persist Security Info=True;User ID=chncmadb;Data Source=towebserver"AdoRs.Open "select * from T320481TR012004", AdoCnn, adOpenDynamic, adLockPessimistic, adCmdTextSet DataGrid1.DataSource = AdoRsSet AdoRs = NothingSet AdoCnn = NothingEnd Sub5.'ADO代码与SQLserver数据库连接'未测试Private Sub Command5_Click()Dim AdoCnn As ADODB.ConnectionDim AdoRs As ADODB.RecordsetSet AdoCnn = New ADODB.ConnectionSet AdoRs = New ADODB.RecordsetAdoCnn.CursorLocation = adUseClient'.open后面的字符串可以参考ADO控件连接.ConnectionString后面的的字符串AdoCnn.Open "Provider=SQLOLEDB.1;Password=111;Persist Security Info=True;User ID=111;Initial Catalog=111;Data Source=111"AdoRs.Open "select * from T320481TR012004", AdoCnn, adOpenDynamic, adLockPessimistic, adCmdTextSet DataGrid1.DataSource = AdoRsSet AdoRs = NothingSet AdoCnn = NothingEnd Sub。

VB与数据库的连接步骤以相关语句

VB与数据库的连接步骤以相关语句

vb6.0连接sql2000数据库的具体步骤1.定义连接对象Global DBconnect As New ADODB.Connection2.执行连接语句If DBconnect.State = adStateOpen And Not IsEmpty(adStateOpen) Then DBconnect.Closel连接ODBC DBconnect.ConnectionString = "dsn1.定义连接对象Global DBconnect As New ADODB.Connection2.执行连接语句If DBconnect.State = adStateOpen And Not IsEmpty(adStateOpen) ThenDBconnect.Closel连接ODBCDBconnect.ConnectionString="dsn=DataAliasName;uid=UserID;pwd=Passwd;"l直接连接Access为Dbconnect.Provider = "Microsoft.jet.OLEDB.4.0" // Access 97为3.51DBconnect.ConnectionString = "FilePathFileName.mdb"l连接OracleDBconnect.Provider = "MSADORA"DBconnect.ConnectionString = "user/mypass@servicenamel连接SQL ServerDBconnect.Provider = "SQLOLEDB.1"DBconnect.ConnectionString = "DATABASE= ;SERVER= ;UID= ;PWD= ;"或者可以使用DBconnect.Open "SERVER" , "USERID" , "PASSWORD" DBConnect.Open3.取查询结果集Global RS As New ADODB.RecordsetGlobal PS As New ADODB.RecordsetIf RS.State = adStateOpen And Not IsEmpty(adStateOpen) Then RS.CloseRS.Open SQLStr, DBconnect, adOpenKeyset4.执行SQL语句DBconn.Execute SQLStrPDF 文件使用 "pdfFactory Pro" 试用版本创建5.关闭数据库DBconnect.CloseVB使用ADO数据库可以分为有源数据库和无源数据库,即是否使用了DSN数据源,如下例:1、在连接数据库前首先要在VB菜单中“工程”-“引用”从中选择microsoft activeXData objects 2.6 library和microsoft activeX Data objects recordset 2.6两个组件,这是在连接数据前所必做的工作。

vb教程--数据库连接

vb教程--数据库连接

Vb数据库连接vb数据库操作是初学者普遍感到头疼的地方,因为现有的vb教材和资料中的数据库操作这部分,多是泛泛而谈或是一带而过。

因此就想组织一个包括添加、修改、删除这些基本功能的数据库操作实例供大家参考。

久已未用vb6,机器里已经装上了VS 2008,再改回vb6,感觉实在是怪怪的。

还好有朋友帮忙,感谢“小二黑”网友供稿!也许有朋友觉得vb6版本已经很低了,做这个事还有意义吗?其实对微软来说,vb5是vb,vb6是vb,中的也是vb;而对于许多初学者来说,vb只是vb6,为什么这么说呢?因为对于许多不了解编程的朋友来说,似乎vb就是编程的代名词,学编程的第一反应就是学vb,而民间的电脑培训学校开设的多数都是vb6课程,那么他们学到的都是vb6;同时计算机等级考试也可以用vb6来过级,有相当部分的朋友是为了考证而学编程的,你相信他会放着简单易学的vb6不学,而去研究庞大的.NET吗?因此我觉得这个事还是值得去做的,所以就有了下面这几篇文章。

第一部分:vb数据库操作实例vb教程(续)--编写一个小型的信息管理系统vb教程(续)--准备数据库vb教程(续)--设计系统的界面及对象的属性vb教程(续)--为对象添加事件代码第二部分:补充内容vb教程(续)--ODBC数据源简介vb教程(续)--配置Access数据源vb教程(续)---配置SQL Server数据源vb教程(续)--VB的ADO对象vb教程(续)--vb adodb Connection对象简介vb教程(续)--vb连接Access数据库实例vb教程(续)--使用ADO Data控件连接Access的简单实例vb教程(续)--编写一个小型的信息管理系统受委托为编程入门网做一个简单的vb操作数据库的实例,来演示一下如何用vb向数据库中添加、修改、删除记录这些操作。

我觉得自己是比较菜的,几年来别人都在进步,只有我还在原地踏步。

不过没有办法,我们这一圈人里现在只有我机器上还有vb6,勉为其难,只有尝试一下了。

VBA中数据库连接的技巧与方法

VBA中数据库连接的技巧与方法

VBA中数据库连接的技巧与方法VBA(Visual Basic for Applications)是一种广泛应用于Microsoft Office软件中的编程语言,通过VBA,用户可以自动化执行各种操作,包括与数据库的连接与数据操作。

在本文中,我们将探讨VBA中数据库连接的技巧与方法,帮助读者更好地利用VBA进行数据库操作。

1. VBA中的数据库连接对象在VBA中,我们可以使用ADODB(ActiveX Data Objects Database)库来创建数据库连接对象。

ADODB库提供了多种数据库连接方式,包括ODBC(Open Database Connectivity)、ODBC数据源名称(DSN)和本地数据源,以便于连接各种类型的数据库,比如Access、SQL Server、Oracle等。

使用ADODB的示例代码如下:```vbaDim conn As ObjectSet conn = CreateObject("ADODB.Connection")conn.ConnectionString ="Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\YourDatabase.mdb;"conn.Open```上述代码创建了一个conn对象,并指定了连接字符串,连接字符串中包含了数据库的驱动程序(Provider)和数据源(Data Source)信息。

这里假设我们连接的是Access数据库。

2. 连接到不同类型的数据库可以根据不同类型的数据库调整连接字符串。

下面是一些常见数据库的连接字符串示例:- Access数据库:```vbaconn.ConnectionString ="Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\YourDatabase.mdb;"```- SQL Server数据库:```vbaconn.ConnectionString = "Provider=SQLOLEDB;Data Source=YourServer;Initial Catalog=YourDatabase;UserID=YourUsername;Password=YourPassword;"```- Oracle数据库:```vbaconn.ConnectionString ="Provider=OraOLEDB.Oracle;Data Source=YourServer;User ID=YourUsername;Password=YourPassword;"```通过修改连接字符串,可以连接到不同类型的数据库。

vba 联合字符串函数

vba 联合字符串函数

vba 联合字符串函数VBA中有多种方法可以联合字符串,下面我会介绍几种常用的方法。

首先,我们可以使用“&”符号来连接字符串。

例如,如果我们有两个字符串变量str1和str2,我们可以使用以下代码将它们连接起来:vba.Dim str1 As String.Dim str2 As String.Dim combinedStr As String.str1 = "Hello"str2 = "World"combinedStr = str1 & " " & str2。

在这个例子中,combinedStr的值将会是“Hello World”。

其次,我们也可以使用VBA中的Concatenate函数来联合字符串。

这个函数可以接受多个参数,并将它们连接起来。

例如:vba.Dim combinedStr As String.combinedStr = WorksheetFunction.Concatenate("Hello", " ", "World")。

这段代码也会将combinedStr的值设置为“Hello World”。

另外,我们还可以使用VBA中的字符串连接函数Join来连接一个数组中的字符串。

例如:vba.Dim arr(0 To 1) As String.arr(0) = "Hello"arr(1) = "World"Dim combinedStr As String.combinedStr = Join(arr, " ")。

在这个例子中,combinedStr的值同样会是“Hello World”。

除了以上介绍的方法,我们还可以使用字符串处理函数如Mid、Left、Right等来截取和连接字符串。

vb中join用法

vb中join用法

vb中join用法在VB中,Join函数用于将一个字符串数组的元素连接起来,形成一个新的字符串。

它的语法如下:Join(要连接的字符串数组, 连接符)。

其中,要连接的字符串数组是一个包含多个字符串元素的数组,连接符是可选的,用于指定连接字符串之间的分隔符。

Join函数的使用可以从多个角度来解释和使用,下面我将从以下几个方面来详细介绍。

1. 连接字符串数组:Join函数的主要作用是将字符串数组的元素连接起来形成一个新的字符串。

例如,我们有一个包含三个元素的字符串数组arr,可以使用Join函数将数组元素连接成一个字符串:Dim arr() As String = {"Hello", "World", "!"}。

Dim result As String = Join(arr)。

上述代码将返回一个新的字符串result,其内容为"Hello World!"。

2. 指定连接符:Join函数的第二个参数是可选的连接符,用于指定连接字符串之间的分隔符。

如果不指定连接符,则默认使用空字符串作为分隔符。

例如,我们可以指定一个空格作为连接符来连接字符串数组的元素:Dim arr() As String = {"Hello", "World", "!"}。

Dim result As String = Join(arr, " ")。

上述代码将返回一个新的字符串result,其内容为"Hello World !"。

3. 处理不同数据类型:Join函数不仅可以连接字符串数组,还可以连接其他类型的数组。

当连接其他类型的数组时,Join函数会将数组元素自动转换为字符串。

例如,我们有一个包含整数元素的数组arr,可以使用Join函数连接该数组的元素:Dim arr() As Integer = {1, 2, 3}。

vb数据库连接字符串

vb数据库连接字符串

***************************************************************************** 使用adodb.stream 保存/读取文件到数据库** 引用microsoft activex data objects 2.5 library 及以上版本**** ----- 数据库连接字符串模板---------------------------------------** access数据库** iconcstr = "provider=microsoft.jet.oledb.4.0;persist security info=false" & _** ";data source=数据库名"**** sql数据库** iconcstr = "provider=sqloledb.1;persist security info=true;" & _** "user id=用户名;password=密码;initial catalog=数据库名;data source=sql服务器名"***************************************************************************保存文件到数据库中sub s_savefile()dim istm as adodb.streamdim ire as adodb.recordsetdim iconcstr as string数据库连接字符串iconcstr = "provider=microsoft.jet.oledb.4.0;persist security info=false" & _";data source=f:/my documents/客户资料1.mdb"读取文件到内容set istm = new adodb.streamwith istm.type = adtypebinary 二进制模式.open.loadfromfile "c:/test.doc"end with打开保存文件的表set ire = new adodb.recordsetwith ire.open "表", iconc, adopenkeyset, adlockoptimistic.addnew 新增一条记录.fields("保存文件内容的字段") = istm.read.updateend with完成后关闭对象ire.closeistm.closeend sub从数据库中读取数据,保存成文件sub s_readfile()dim istm as adodb.streamdim ire as adodb.recordsetdim iconc as string数据库连接字符串iconc = "provider=microsoft.jet.oledb.4.0;persist security info=false" & _";data source=//xz/c$/inetpub/zj/zj/zj.mdb"打开表set ire = new adodb.recordsetire.open "tb_img", iconc, adopenkeyset, adlockreadonly ire.filter = "id=64"保存到文件set istm = new adodb.streamwith istm.mode = admodereadwrite.type = adtypebinary.open.write ire("img").savetofile "c:/test.doc"end with关闭对象ire.closeistm.closeend subdim cn as new adodb.connectiondim rs as new adodb.recordsetdim stm as adodb.streamprivate sub savepicturetodb(cn as adodb.connection)将bmp图片存入数据库on error goto ehset stm = new adodb.streamrs.open "select imagepath,imagevalue from tbl_image", cn, adope nkeyset, adlockoptimisticcommondialog1.showopentext1.text = commondialog1.filenamewith stm.type = adtypebinary.open.loadfromfile commondialog1.filenameend withwith rs.addnew.fields("imagepath") = text1.text.fields("imagevalue") = stm.read.updateend withset rs = nothingexit subeh: msgbox err.description, vbinformation, "error"end subprivate sub loadpicturefromdb(cn as adodb.connection)载数据库中读出bmp图片on error goto ehdim strtemp as stringset stm = new adodb.streamstrtemp = "c:/temp.tmp" 临时文件,用来保存读出的图片rs.open "select imagepath,imagevalue from tbl_image", cn, , , adcmdtextwith stm.type = adtypebinary.open.write rs("imagevalue").savetofile strtemp, adsavecreateoverwrite.closeimage1.picture = loadpicture(strtemp)set stm = nothingrs.closeset rs = nothingexit subeh: msgbox err.description, vbinformation, "error"end subimage类型用picture显示以下两个函数是从数据库中读出图片的核心程序public function getimage(optional filename as string) as variant on error goto procerrdim objrs as adodb.recordsetdim strsql as stringdim chunk() as byteset objrs = new adodb.recordsetstrsql = "select thumb from tblpictures where idpict=" & tblid(thu mbindex) & ""strsql = "select thumb from tblpictures where idpict= " & thum bstrsql = "select thumb from tblpictures where idpict=387"db.execute strsqlobjrs.open strsql, db, adopenforwardonly, adlockreadonlyif objrs.bof and objrs.eof thengetimage = 0goto procexitelseif isnull(objrs.fields(0)) thenerrnumber = 1001errdesc = "字段为空"goto procexitend ifchunk() = objrs.fields(0).getchunk(objrs.fields(0).actualsize)set getimage = chunk2image(chunk(), filename)procexit:on error resume nextobjrs.closechunk() = objrs.fields(0).getchunk(0)set getimage = chunk2image(chunk(), filename)set objrs = nothingexit functionprocerr:getimage = 0resume procexitend functionprivate function chunk2image(chunk() as byte, optional filename as st ring) as varianton error goto procerrdim keepfile as booleandim datafile as integerkeepfile = trueif trim(filename) = "" thenfilename = "c:/tmpxxdb.fil"keepfile = falseend ifdatafile = freefileopen filename for binary access write as datafile put datafile, , chunk()close datafileprocexit:set chunk2image = loadpicture(filename)on error resume nextif not keepfile then kill filenameexit functionprocerr:on error resume nextkill filenamechunk2image = 0end functionpublic function getfromfile(strtable as string, strfield as string, strfilter as string, objfilename as string) as boolean============================================================过程函数名:commmodule.getfromfile类型:function参数:strtable (string):准备保存图形数据的表名称strfield (string):准备保存图形数据的字段名称strfilter (string):打开表的过滤字符串,用于定位并确保被打开的表的数据的唯一性objfilename (string) :准备输入到表里边的图象文件名称返回:如果保存成功,返回true,如果失败,返回false-------------------------------------------------------------说明:把图象文件的数据保存到表里边-------------------------------------------------------------修订历史:=============================================================dim recset as adodb.recordset, filedata() as byte, fileno as lon g, filesize as long, strsql as stringstrsql = "select " & strfield & " from " & strtable & " where " & strfilter & ";"set recset = new adodb.recordsetrecset.open strsql, currentproject.connection, adopendynamic, adlockopti misticgetfromfile = trueif recset(strfield).type <> db_ole or not isfilename(objfilename) thengetfromfile = false如果字段不是ole字段,或者文件不存在,返回错误goto endgetfromfileend ifif recset.eof then如果记录不存在,返回错误getfromfile = falsegoto endgetfromfileend iffilesize = getfilesize(objfilename) 如果被打开的文件大小为零,返回错误if filesize <= 0 thengetfromfile = falsegoto endgetfromfileend ifredim filedata(filesize)重新初始化数组fileno = freefile获取一个空闲的文件号open objfilename for binary as #fileno打开文件get #fileno, , filedata()读取文件内容到数组close #fileno关闭文件recset(strfield).value = filedata() 保存数据recset.update更新数据erase filedata释放内存endgetfromfile:recset.close关闭recordsetset recset = nothing释放内存end functionpublic function savetofile(strtable as string, strfield as string, strfilter as string, strfilename as string) as boolean============================================================过程函数名:commmodule.savetofile 类型:function参数:strtable (string):保存图形数据的表名称strfield (string):保存图形数据的字段名称strfilter (string):打开表的过滤字符串,用于定位并确保被打开的表的纪录的唯一性strfilename (string) :准备保存的图象的文件名称返回:如果保存成功,返回true,如果失败,返回false-------------------------------------------------------------说明:把由getfromfile函数保存到表中ole字段的数据还原到文件-------------------------------------------------------------修订历史:=============================================================dim recset as adodb.recordset, filedata() as byte, fileno as lon g, filesize as long, strsql as stringstrsql = "select " & strfield & " from " & strtable & " where " & strfilter & ";"set recset = new adodb.recordsetrecset.open strsql, currentproject.connection, adopendynamic, adlockopti misticsavetofile = trueif recset(strfield).type <> db_ole thensavetofile = false如果字段不是ole字段,返回错误goto endsavetofileend ifif recset.eof then如果记录不存在,返回错误savetofile = falsegoto endsavetofileend iffileno = freefileopen strfilename for binary as #filenoredim filedata(recset(strfield).actualsize) 重新初始化数组filedata() = recset(strfield).getchunk(recset(strfield).actualsize) 把ole字段的内容保存到数组put #fileno, , filedata()把数组内容保存到文件close #filenoerase filedataendsavetofile:recset.closeset recset = nothingend function。

数据库连接字符串大全

数据库连接字符串大全

•SQL Server• ODBCo Standard Security:"Driver={SQL Server};Server=Aron1;Database=pubs;Uid=sa;Pwd=asdasd;"o Trusted connection:"Driver={SQL Server};Server=Aron1;Database=pubs;Trusted_Connection=yes;"o Prompt for username and password:oConn.Properties("Prompt") = adPromptAlwaysoConn.Open "Driver={SQL Server};Server=Aron1;DataBase=pubs;"• OLE DB, OleDbConnection (.NET)o Standard Security:"Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;UserId=sa;Password=asdasd;"o Trusted Connection:"Provider=sqloledb;Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"(use serverName\instanceName as Data Source to use an specifik SQLServer instance,only SQLServer2000)o Prompt for username and password:oConn.Provider = "sqloledb"oConn.Properties("Prompt") = adPromptAlwaysoConn.Open "Data Source=Aron1;Initial Catalog=pubs;"o Connect via an IP address:"Provider=sqloledb;Data Source=190.190.200.100,1433;NetworkLibrary=DBMSSOCN;Initial Catalog= pubs;UserID=sa;Password=asdasd;"(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the portto use (1433 is the default))• SqlConnection (.NET)o Standard Security:"Data Source=Aron1;Initial Catalog= pubs;UserId=sa;Password=asdasd;"- or -"Server=Aron1;Database=pubs;UserID=sa;Password=asdasd;Trusted_Connection=False"(booth connection strings produces the same result)o Trusted Connection:"Data Source=Aron1;Initial Catalog=pubs;Integrated Security=SSPI;"- or -< BR>"Server=Aron1;Database=pubs;Trusted_Connection=True;"(booth connection strings produces the same result)(use serverName\instanceName as Data Source to use an specifik SQLServer instance,only SQLServer2000)o Connect via an IP address:"Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;UserID=sa;Password=asdasd;"(DBMSSOCN=TCP/IP instead of Named Pipes, at the end of the Data Source is the portto use (1433 is the default))o Declare the SqlConnection:C#:using System.Data.SqlClient;SqlConnection oSQLConn = new SqlConnection();oSQLConn.ConnectionString="my connectionstring";oSQLConn.Open();:Imports System.Data.SqlClientDim oSQLConn As SqlConnection = New SqlConnection()oSQLConn.ConnectionString="my connectionstring"oSQLConn.Open()• Data Shapeo MS Data Shape"Provider=MSDataShape;Data Provider=SQLOLEDB;Data Source=Aron1;Initial Catalog=pubs;UserID=sa;Password=asdasd;"Want to learn data shaping? Check out 4GuyfFromRolla's great article about DataShaping >>• Read moreo How to define wich network protocol to useExample:"Provider=sqloledb;Data Source=190.190.200.100,1433;NetworkLibrary=DBMSSOCN;Initial Catalog= pubs;UserID=sa;Password=asdasd;"Name Network librarydbnmpntw Win32 Named Pipesdbmssocn Win32 Winsock TCP/IPdbmsspxn Win32 SPX/IPXdbmsvinn Win32 Banyan Vinesdbmsrpcn Win32 Multi-Protocol (Windows RPC)Important note!When connecting through the SQLOLEDB provider use the syntax Network Library=dbmssocnand when connecting through MSDASQL provider use the syntax Network=dbmssocno All SqlConnection connectionstring propertiesThis table shows all connectionstring properties for the SqlConnectionobject. Most of the properties are also used in ADO. All properties anddescriptions is from msdn.Name Default DescriptionApplication Name The name of the application, or '.Net SqlClientData Provider' if no application name isprovided.AttachDBFilename -or-extended properties -or-Initial File Name The name of the primary file, including the full path name, of an attachable database. The database name must be specified with the keyword 'database'.Connect Timeout -or-Connection Timeout 15 The length of time (in seconds) to wait for aconnection to the server before terminatingthe attempt and generating an error.Connection Lifetime0 When a connection is returned to the pool, itscreation time is compared with the currenttime, and the connection is destroyed if thattime span (in seconds) exceeds the valuespecified by connection lifetime. Useful inclustered configurations to force loadbalancing between a running server and aserver just brought on-line.Connection Reset 'true' Determines whether the database connectionis reset when being removed from the pool.Setting to 'false' avoids making an additionalserver round-trip when obtaining a connection,but the programmer must be aware that theconnection state is not being reset.Current Language The SQL Server Language record name.Data Source-or-Server-or-Address-or-Addr-or-Network Address The name or network address of the instance of SQL Server to which to connect.Enlist 'true' When true, the pooler automatically enlists theconnection in the creation thread's currenttransaction context.Initial Catalog-or-DatabaseThe name of the database.Integrated Security -or-Trusted_Connection 'false' Whether the connection is to be a secureconnection or not. Recognized values are'true', 'false', and 'sspi', which is equivalent to'true'.Max Pool Size 100 The maximum number of connections allowedin the pool.Min Pool Size 0 The minimum number of connections allowedin the pool.Network Library -or-Net 'dbmssocn'The network library used to establish aconnection to an instance of SQL Server.Supported values include dbnmpntw (NamedPipes), dbmsrpcn (Multiprotocol), dbmsadsn(Apple Talk), dbmsgnet (VIA), dbmsipcn(Shared Memory) and dbmsspxn (IPX/SPX),and dbmssocn (TCP/IP).The corresponding network DLL must beinstalled on the system to which you connect.If you do not specify a network and you use alocal server (for example, "." or "(local)"),shared memory is used.Packet Size 8192 Size in bytes of the network packets used tocommunicate with an instance of SQL Server.Password -or-Pwd The password for the SQL Server account logging on.Persist Security Info'false' When set to 'false', security-sensitiveinformation, such as the password, is notreturned as part of the connection if theconnection is open or has ever been in anopen state. Resetting the connection stringresets all connection string values includingthe password.Pooling 'true' When true, the SQLConnection object isdrawn from the appropriate pool, or ifnecessary, is created and added to theappropriate pool.User ID The SQL Server login account.Workstation ID the localcomputername The name of the workstation connecting to SQL Server.NoteUse ; to separate each property.If a name occurs more than once, the value from the last one in the connectionstring will be used.If you are building your connectionstring in your app using values from user input fields, make sure the user can'tchange the connectionstring by inserting an additional property with another value within the user value. •Access• ODBCo Standard Security:"Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;"o Workgroup:"Driver={Microsoft Access Driver(*.mdb)};Dbq=C:\mydatabase.mdb;SystemDB=C:\mydatabase.mdw;"o Exclusive:"Driver={Microsoft Access Driver(*.mdb)};Dbq=C:\mydatabase.mdb;Exclusive=1;Uid=admin;Pwd="• OLE DB, OleDbConnection (.NET)o Standard security:"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;UserId=admin;Password=;"o Workgroup (system database):"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;JetOLEDB:System Database=system.mdw;"o With password:"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\somepath\mydb.mdb;JetOLEDB:Database Password=MyDbPassword;"• Oracle• ODBCo New version:"Driver={Microsoft ODBC forOracle};Server=OracleServer.world;Uid=Username;Pwd=asdasd;"o Old version:"Driver={Microsoft ODBC Driver forOracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;" • OLE DB, OleDbConnection (.NET)o Standard security:"Provider=msdaora;Data Source= MyOracleDB;UserId=UserName;Password=asdasd;"This one's from Microsoft, the following are from Oracleo Standard Security:"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;UserId=Username;Password=asdasd;"o Trusted Connection:"Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;"• OracleConnection (.NET)o Standard:"Data Source=Oracle8i;Integrated Security=yes";This one works only with Oracle 8i release 3 or latero Declare the OracleConnection:C#:using System.Data.OracleClient;OracleConnection oOracleConn = new OracleConnection();oOracleConn.ConnectionString = "my connectionstring";oOracleConn.Open();:Imports System.Data.OracleClientDim oOracleConn As OracleConnection = New OracleConnection()oOracleConn.ConnectionString = "my connectionstring"oOracleConn.Open()• Core Labs OraDirect (.NET)o Standard:"User ID=scott; Password=tiger; Host=ora; Pooling=true; Min Pool Size=0;Max PoolSize=100; Connection Lifetime=0"Read more at Core Lab and the product page.• Data Shapeo MS Data Shape:"Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;DataSource= orac;userid=username;password=mypw"Want to learn data shaping? Check out 4GuyfFromRolla's great article about DataShaping >>• MySQL• ODBCo Local database:"Driver={mySQL};Server=mySrvName;Option=16834;Database=mydatabase;"o Remote database:"Driver={mySQL};Server=;Port=3306;Option=131072;Stmt=;Database=my-database;Uid=username;Pwd=password;"• OLE DB, OleDbConnection (.NET)o Standard:"Provider=MySQLProv;Data Source=mydb;User Id=UserName;Password=asdasd;"• MySqlConnection (.NET)o eInfoDesigns.dbProvider:"DataSource=server;Database= mydb;UserID=username;Password=pwd;CommandLogging=false"This one is used with eInfoDesigns dbProvider, an add-on to .NETo Declare the MySqlConnection:C#:using eInfoDesigns.dbProvider.MySqlClient;MySqlConnection oMySqlConn = new MySqlConnection();oMySqlConn.ConnectionString = "my connectionstring";oMySqlConn.Open();:Imports eInfoDesigns.dbProvider.MySqlClientDim oMySqlConn As MySqlConnection = New MySqlConnection()oMySqlConn.ConnectionString = "my connectionstring"oMySqlConn.Open()• SevenObjects MySqlClient (.NET)o Standard:"Host=server; UserName= myusername;Password=mypassword;Database=mydb;"This is a freeware data provider from SevenObjects• Core Labs MySQLDirect (.NET)o Standard:"User ID=root; Password=pwd; Host=localhost; Port= 3306;Database=test;Direct=true;Protocol=TCP; Compress=false; Pooling=true; Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0"Read more at Core Lab and the product page.•Interbase• ODBC, Easysofto Local computer:"Driver={Easysoft IB6ODBC};Server=localhost;Database=localhost:C:\mydatabase.gdb;Uid=username;Pwd=password"o Remote Computer:< DIV>"Driver={EasysoftIB6ODBC};Server=ComputerName;Database=ComputerName:C:\mydatabase.gdb;Uid=username;Pwd=password"Read more about this driver: Easysoft ODBC-Interbase driver >>• ODBC, Intersolvo Local computer:"Driver={INTERSOLV InterBase ODBC Driver(*.gdb)};Server=localhost;Database=localhost:C:\mydatabase.gdb;Uid=username;Pwd=password"o Remote Computer:"Driver= {INTERSOLVInterBaseODBCDriver(*.gdb)};Server=ComputerName;Database=ComputerName:C:\mydatabase.gdb;Uid=username;Pwd=password"This driver are provided by DataDirect Technologies >> (formerly Intersolv)• OLE DB, SIBPROvidero Standard:"provider=sibprovider;location=localhost:;datasource=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey"o Specifying character set:"provider=sibprovider;location=localhost:;datasource=c:\databases\gdbs\mygdb.gdb;user id=SYSDBA;password=masterkey;characterset=ISO8859_1"o Specifying role:"provider=sibprovider;location=localhost:;datasource=c:\databases\gdbs\mygdb.gdb;userid=SYSDBA;password=masterkey;role=DIGITADORES"Read more about SIBPROvider >>•Read more about connecting to Interbase in this Borland Developer Network article/article/0,1410,27152,00.html• IBM DB2• OLE DB, OleDbConnection (.NET) from mso TCP/IP:"Provider=DB2OLEDB;Network Transport Library=TCPIP;NetworkAddress=XXX.XXX.XXX.XXX;Initial Catalog=MyCtlg;PackageCollection=MyPkgCol;Default Schema=Schema;User ID=MyUser;Password=MyPW"o APPC:"Provider=DB2OLEDB;APPC Local LU Alias=MyAlias;APPC Remote LUAlias=MyRemote;Initial Catalog=MyCtlg;Package Collection=MyPkgCol;DefaultSchema=Schema;User ID=MyUser;Password=MyPW"•Sybaseo Standard Sybase System 12 (or 12.5) Enterprise Open Client:"Driver={SYBASE ASE ODBC Driver};Srvr=Aron1;Uid=username;Pwd=password"o Standard Sybase System 11:"Driver= {SYBASESYSTEM11};Srvr=Aron1;Uid=username;Pwd=password;"Do you know a userguide for Sybase System 11, 12, 12.5? E-mail the URL to now!! >>o Intersolv 3.10:"Driver={INTERSOLV 3.10 32-BIT Sybase};Srvr=Aron1;Uid=username;Pwd=password;"o Sybase SQL Anywhere (former Watcom SQL ODBC driver):"ODBC; Driver=SybaseSQLAnywhere5.0;DefaultDir=c:\dbfolder\;Dbf=c:\mydatabase.db;Uid=username;P wd=password;Dsn="""""Note! The two double quota following the DSN parameter at the end are escaped quotas (VB syntax), you may have to change this to your language specific escape syntax. The empty DSN parameter is indeed critical as not including it will result in error 7778.Read more in the Sybase SQL Anywhere User Guide >>o Adaptive Server Anywhere (ASA):"Provider=ASAProv;Data source=myASA"Read more in the ASA User Guide >>o Adaptive Server Enterprise (ASE) with Data Source .IDS file:"Provider=Sybase ASE OLE DB Provider; Data source=myASE"Note that you must create a Data Source .IDS file using the Sybase Data Administrator.These .IDS files resemble ODBC DSNs.o Adaptive Server Enterprise (ASE):< DIV>"Provider=Sybase.ASEOLEDBProvider;Srvr=myASEserver,5000;Catalog=myDBname;UserId=username;Password=password"- some reports on problem using the above one, try the following as an alternative -"Provider=Sybase.ASEOLEDBProvider;Server Name=myASEserver,5000;InitialCatalog= myDBname;UserId=username;Password=password"This one works only from Open Client 12.5 where the server port number feature works,燼llowing fully qualified connection strings to be used without defining燼ny .IDS DataSource files.•Informix• ODBCo Informix 3.30:"Dsn='';Driver={INFORMIX 3.30 32BIT};Host=hostname;Server=myserver;Service=service-name;Protocol=olsoctcp;Database=mydb;UID=username;PWD=myPwdo Informix-CLI 2.5:"Driver={Informix-CLI 2.5 (32Bit)};Server=myserver;Database=mydb;Uid=username;Pwd=myPwd"• OLE DBo IBM Informix OLE DB Provider:"Provider=Ifxoledbc.2;password=myPw;User ID=myUser;DataSource=dbName@serverName;Persist Security Info=true"•Mimer SQL• ODBCo Standard Security:"Driver={MIMER};Database=mydb;Uid=myuser;Pwd=mypw;"o Prompt for username and password:"Driver={MIMER};Database=mydb;"•PostgreSQL• Core Labs PostgreSQLDirect (.NET)o Standard:"User ID=root; Password=pwd; Host=localhost; Port=5432;Database=testdb;Pooling=true; Min Pool Size=0; Max Pool Size=100; ConnectionLifetime=0"Read more at Core Lab and the product page.•DSN• ODBCo DSN:"DSN=myDsn;Uid=username;Pwd=;"o File DSN:"FILEDSN=c:\myData.dsn;Uid=username;Pwd=;"• Excel• ODBCo Standard:"Driver={Microsoft Excel Driver(*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath;"• OLE DBo Standard:"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;ExtendedProperties=""Excel 8.0;HDR=Yes;IMEX=1""""HDR=Yes;" indicates that the first row contains columnnames, not data"IMEX=1;" tells the driver to always read "intermixed" data columns as textTIP! SQL syntax: "SELECT * FROM [sheet1$]" - i.e. worksheet name followed by a "$"and wrapped in "[" "]" brackets.• Text• ODBCo Standard:"Driver={Microsoft Text Driver (*.txt;*.csv)};Dbq=c:\txtFilesFolder\;Extensions=asc,csv,tab,txt;"• OLE DBo Standard:< DIV> "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=c:\txtFilesFolder\;ExtendedProperties=""text;HDR=Yes;FMT=Delimited""""HDR=Yes;" indicates that the first row contains columnnames, not data•DBF / FoxPro• ODBCo standard:"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=c:\mydbpath;"• OLE DB, OleDbConnection (.NET)o standard:"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\folder;Extended Properties=dBASEIV;User ID=Admin;Password="•Visual FoxPro• OLE DB, OleDbConnection (.NET)o Database container (.DBC):"Provider=vfpoledb.1;DataSource=C:\MyDbFolder\MyDbContainer.dbc;Password=MyPassWord;CollatingSequence=machine"o Free table directory:"Provider=vfpoledb.1;DataSource=C:\MyDataDirectory\;Password=MyPassWord;Collating Sequence=general"Read more (Microsoft msdn) >>• ODBCo Database container (.DBC):"Driver={Microsoft Visual FoxProDriver};SourceType=DBC;SourceDB=c:\myvfpdb.dbc;Exclusive=No;Collate=Machine;"o Free Table directory:"Driver={MicrosoftVisualFoxProDriver};SourceType=DBF;SourceDB=c:\myvfpdbfolder;Exclusive=No;Collate=Machine;""Collate=Machine" is the default setting, for other settings check the list of supportedcollating sequences >>•Microsoft Visual Foxpro site: /vfoxpro•Pervasive• ODBCo Standard:"Driver= {Pervasive ODBC ClientInterface};ServerName=srvname;dbq=@dbname"Pervasive ODBC info >>• OLE DBo Standard:"Provider=PervasiveOLEDB;Data Source=C:\path"Pervasive OLE DB info >>•UDL• UDLo UDL:"File Name=c:\myDataLink.udl;"。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

***************************************************************************** 使用adodb.stream 保存/读取文件到数据库** 引用microsoft activex data objects 2.5 library 及以上版本**** ----- 数据库连接字符串模板---------------------------------------** access数据库** iconcstr = "provider=microsoft.jet.oledb.4.0;persist security info=false" & _** ";data source=数据库名"**** sql数据库** iconcstr = "provider=sqloledb.1;persist security info=true;" & _** "user id=用户名;password=密码;initial catalog=数据库名;data source=sql服务器名"***************************************************************************保存文件到数据库中sub s_savefile()dim istm as adodb.streamdim ire as adodb.recordsetdim iconcstr as string数据库连接字符串iconcstr = "provider=microsoft.jet.oledb.4.0;persist security info=false" & _";data source=f:/my documents/客户资料1.mdb"读取文件到内容set istm = new adodb.streamwith istm.type = adtypebinary 二进制模式.open.loadfromfile "c:/test.doc"end with打开保存文件的表set ire = new adodb.recordsetwith ire.open "表", iconc, adopenkeyset, adlockoptimistic.addnew 新增一条记录.fields("保存文件内容的字段") = istm.read.updateend with完成后关闭对象ire.closeistm.closeend sub从数据库中读取数据,保存成文件sub s_readfile()dim istm as adodb.streamdim ire as adodb.recordsetdim iconc as string数据库连接字符串iconc = "provider=microsoft.jet.oledb.4.0;persist security info=false" & _";data source=//xz/c$/inetpub/zj/zj/zj.mdb"打开表set ire = new adodb.recordsetire.open "tb_img", iconc, adopenkeyset, adlockreadonlyire.filter = "id=64"保存到文件set istm = new adodb.streamwith istm.mode = admodereadwrite.type = adtypebinary.open.write ire("img").savetofile "c:/test.doc"end with关闭对象ire.closeistm.closeend subdim cn as new adodb.connectiondim rs as new adodb.recordsetdim stm as adodb.streamprivate sub savepicturetodb(cn as adodb.connection)将bmp图片存入数据库on error goto ehset stm = new adodb.streamrs.open "select imagepath,imagevalue from tbl_image", cn, adope nkeyset, adlockoptimisticcommondialog1.showopentext1.text = commondialog1.filenamewith stm.type = adtypebinary.open.loadfromfile commondialog1.filenameend withwith rs.addnew.fields("imagepath") = text1.text.fields("imagevalue") = stm.read.updateend withrs.closeset rs = nothingexit subeh: msgbox err.description, vbinformation, "error"end subprivate sub loadpicturefromdb(cn as adodb.connection)载数据库中读出bmp图片on error goto ehdim strtemp as stringset stm = new adodb.streamstrtemp = "c:/temp.tmp" 临时文件,用来保存读出的图片rs.open "select imagepath,imagevalue from tbl_image", cn, , , adcmdtextwith stm.type = adtypebinary.open.write rs("imagevalue").savetofile strtemp, adsavecreateoverwrite.closeend withimage1.picture = loadpicture(strtemp)set stm = nothingrs.closeset rs = nothingexit subeh: msgbox err.description, vbinformation, "error"end subimage类型用picture显示以下两个函数是从数据库中读出图片的核心程序public function getimage(optional filename as string) as varianton error goto procerrdim objrs as adodb.recordsetdim strsql as stringdim chunk() as byteset objrs = new adodb.recordsetstrsql = "select thumb from tblpictures where idpict=" & tblid(thu mbindex) & ""strsql = "select thumb from tblpictures where idpict= " & thum bstrsql = "select thumb from tblpictures where idpict=387"db.execute strsqlobjrs.open strsql, db, adopenforwardonly, adlockreadonlyif objrs.bof and objrs.eof thengetimage = 0goto procexitelseif isnull(objrs.fields(0)) thenerrnumber = 1001errdesc = "字段为空"goto procexitend ifchunk() = objrs.fields(0).getchunk(objrs.fields(0).actualsize)set getimage = chunk2image(chunk(), filename)procexit:on error resume nextobjrs.closechunk() = objrs.fields(0).getchunk(0)set getimage = chunk2image(chunk(), filename)set objrs = nothingexit functionprocerr:getimage = 0resume procexitend functionprivate function chunk2image(chunk() as byte, optional filename as st ring) as varianton error goto procerrdim keepfile as booleandim datafile as integerkeepfile = trueif trim(filename) = "" thenfilename = "c:/tmpxxdb.fil"keepfile = falseend ifdatafile = freefileopen filename for binary access write as datafileput datafile, , chunk()close datafileprocexit:set chunk2image = loadpicture(filename)on error resume nextif not keepfile then kill filenameexit functionprocerr:on error resume nextkill filenamechunk2image = 0end functionpublic function getfromfile(strtable as string, strfield as string, strfilter as string, objfilename as string) as boolean============================================================过程函数名:commmodule.getfromfile类型:function参数:strtable (string):准备保存图形数据的表名称strfield (string):准备保存图形数据的字段名称strfilter (string):打开表的过滤字符串,用于定位并确保被打开的表的数据的唯一性objfilename (string) :准备输入到表里边的图象文件名称返回:如果保存成功,返回true,如果失败,返回false-------------------------------------------------------------说明:把图象文件的数据保存到表里边-------------------------------------------------------------修订历史:=============================================================dim recset as adodb.recordset, filedata() as byte, fileno as lon g, filesize as long, strsql as stringstrsql = "select " & strfield & " from " & strtable & " where " & strfilter & ";"set recset = new adodb.recordsetrecset.open strsql, currentproject.connection, adopendynamic, adlockopti misticgetfromfile = trueif recset(strfield).type <> db_ole or not isfilename(objfilename) thengetfromfile = false如果字段不是ole字段,或者文件不存在,返回错误goto endgetfromfileend ifif recset.eof then如果记录不存在,返回错误getfromfile = falsegoto endgetfromfileend iffilesize = getfilesize(objfilename) 如果被打开的文件大小为零,返回错误if filesize <= 0 thengetfromfile = falsegoto endgetfromfileend ifredim filedata(filesize)重新初始化数组fileno = freefile获取一个空闲的文件号open objfilename for binary as #fileno打开文件get #fileno, , filedata()读取文件内容到数组close #fileno关闭文件recset(strfield).value = filedata() 保存数据recset.update更新数据erase filedata释放内存endgetfromfile:recset.close关闭recordsetset recset = nothing释放内存end functionpublic function savetofile(strtable as string, strfield as string, strfilter as string, strfilename as string) as boolean============================================================过程函数名:commmodule.savetofile 类型:function参数:strtable (string):保存图形数据的表名称strfield (string):保存图形数据的字段名称strfilter (string):打开表的过滤字符串,用于定位并确保被打开的表的纪录的唯一性strfilename (string) :准备保存的图象的文件名称返回:如果保存成功,返回true,如果失败,返回false-------------------------------------------------------------说明:把由getfromfile函数保存到表中ole字段的数据还原到文件-------------------------------------------------------------修订历史:=============================================================dim recset as adodb.recordset, filedata() as byte, fileno as lon g, filesize as long, strsql as stringstrsql = "select " & strfield & " from " & strtable & " where " & strfilter & ";"set recset = new adodb.recordsetrecset.open strsql, currentproject.connection, adopendynamic, adlockopti misticsavetofile = trueif recset(strfield).type <> db_ole thensavetofile = false如果字段不是ole字段,返回错误goto endsavetofileend ifif recset.eof then如果记录不存在,返回错误savetofile = falsegoto endsavetofileend iffileno = freefileopen strfilename for binary as #filenoredim filedata(recset(strfield).actualsize) 重新初始化数组filedata() = recset(strfield).getchunk(recset(strfield).actualsize) 把ole字段的内容保存到数组put #fileno, , filedata()把数组内容保存到文件close #filenoerase filedataendsavetofile:recset.closeset recset = nothingend function。

相关文档
最新文档