C#.net Connect various databases

Source: Internet
Author: User
Tags ibm db2 oracleconnection sybase server port


1.c# connections connect to access and Excel
Program code:
-------------------------------------------------------------------------------
Using System.Data;
Using System.Data.OleDb;
..

Stringstrconnection= "Provider=Microsoft.Jet.OLEDB.4.0;";
strconnection+=@ "Data Source=c:begaspnetnorthwind.mdb";

OleDbConnection objconnection=newoledbconnection (strconnection);
..

Objconnection.open ();
Objconnection.close ();
--------------------------------------------------------------------------------

Explain:

Connecting to an Access database requires importing additional namespaces, so it is essential that you have the first two using command!

Strconnection This variable holds the connection string required to connect to the database, specifying the data provider to use and the data source to use.

"Provider=Microsoft.Jet.OLEDB.4.0;" Refers to the data provider, which uses the Microsoft Jet engine, which is the data engine in access, that ASP.net is connected to the Access database.

"Datasource=c:\begaspnet\northwind.mdb" is the location of the data source, and his standard form is "Data Source=mydrive:mypath\myfile.mdb".

Ps:
1. The "@" symbol at the end of "+ =" is to prevent the "\" in the subsequent string from being resolved to an escape character.
2. If the database file you want to connect to is in the same directory as the current file, you can also connect by using the following methods:
strconnection+= "Data source=";
Strconnection+=mappath ("Northwind.mdb";
This will save you from writing a whole lot of stuff!
3. Be aware that the parameters in the connection string are separated by semicolons.

"Oledbconnectionobjconnection=new OleDbConnection (strconnection);" This is the use of a defined connection string to create a linked object, the future operation of the database we have to deal with this object.

"Objconnection.open ();" This is used to open the connection. So far, the connection to the Access database is complete.


97-2003 version

Excel

Provider=Microsoft.Jet.OLEDB.4.0;Data source= file location; Extended Properties=excel 8.0; Hdr=yes;imex=1

ACCESS

Provider=Microsoft.Jet.OLEDB.4.0;Data source= file location; Jet oledb:database password= password;

2007 Version

Excel

provider=microsoft.ace.oledb.12.0;D ata source= file location; Extended properties=Excel 12.0; Hdr=yes;imex=1

ACCESS

provider=microsoft.ace.oledb.12.0;D ata source= file location; Jet oledb:database password= password;

"Other description"

Hdr=yes/no indicates whether the first row is heading.

IMEX indicates whether to cast to text

Special attention

Extended properties= ' Excel 8.0; Hdr=yes;imex=1 '

A:HDR (HeaDer Row) setting

If the specified value is yes, the first row of the worksheet in the Excel file is the field name

If you specify No, the first row on the worksheet that represents the Excel file is data, No field name

B:imex (IMport EXport mode) Setup

IMEX has three modes, each of which causes a different reading and writing behavior, which can be described again:

0 is Export mode

1 is Import mode

2 is linked mode (full update capabilities)

What I specifically want to illustrate here is the IMEX parameter, because different patterns represent different reading and writing behaviors:

When imex=0 is "outbound mode", the Excel file opened in this mode can only be used for "write" purposes.

When Imex=1 is an "import Mode", the Excel file opened in this mode can only be used for "read" purposes.

When imex=2 is "connected mode", the Excel file opened in this mode can support both read and write purposes.
--------------------------------------------------------------------------------

2.c# Connect SQL Server
Program code:
--------------------------------------------------------------------------------

Using System.Data;
Using System.Data.SqlClient;
..

String strconnection= "userid=sa;password=;";
strconnection+= "Initial catalog=northwind; Server=yoursqlserver; ";
strconnection+= "Connect timeout=30";

SqlConnection objconnection=newsqlconnection (strconnection);
..

Objconnection.open ();
Objconnection.close ();
--------------------------------------------------------------------------------

Explain:

The mechanism for connecting to a SQL Server database is not much different from the mechanism for connecting to access, except that different parameters in the Connection object and the connection string are changed.

First, the namespace used to connect to SQL Server is not "System.Data.OleDb", but "System.Data.SqlClient".

And then there's his connection string, and we'll introduce a parameter (note: Separate the parameters by semicolons):
' User Id=sa ': The authentication user name for the connection database is SA. He also has an alias "UID", so we can also write "Uid=sa".
"Password=": The authentication password for the connection database is empty. His alias is "pwd", so we can write it as "pwd=".
Notice here that your SQL Server must have been set up with a username and password to log in, otherwise you won't be able to log in this way. If your SQL Server is set up for Windows login, you don't need to use the user ID and password here. This way to log in, and you need to use "TRUSTED_CONNECTION=SSPI" to log in.
"Initial Catalog=northwind": The data source used is the "Northwind" database. His alias is "database", this sentence can be written as "Database=northwind".
"Server=yoursqlserver": Use a server named "YourSQLServer". His alias is "Data Source", "Address", "Addr". If you are using a local database and you have defined an instance name, you can write as " server= (local) \ instance name; If it is a remote server, replace "(local)" with the name or IP address of the remote server.
"Connect timeout=30": Connection timeout is 30 seconds.

Here, the constructor used to establish the connection object is: SqlConnection.

--------------------------------------------------------------------------------

3.c# Connect Oracle
Program code:
--------------------------------------------------------------------------------
Using System.Data.OracleClient;
Using System.Data;

Add a button to the form called Button1, double-click Button1, and enter the following code
private void Button1_Click (object sender, System.EventArgs e)
{
String connectionstring= "Datasource=sky;user=system;password=manager;";/ /write Connection string
OracleConnection conn=new OracleConnection (ConnectionString);//Create a new connection
Try
{
Conn. Open ();
OracleCommand Cmd=conn. CreateCommand ();

cmd.commandtext= "SELECT * frommytable";/write SQL statements here
OracleDataReader Odr=cmd. ExecuteReader ()//Create a Oracledatereader object
while (ODR. Read ())//reading data, if the ODR. If Read () returns to false, it shows the end of the recordset
{
Response.Write (ODR. Getoraclestring (1). ToString ())//Output field 1, this number is the field index, how to use the field name is still pending research
}
Odr. Close ();
}
catch (Exception ee)
{
Response.Write (EE. message); If there is an error, output the error message
}
Finally
{
Conn. Close (); Close connection
}
}

---------------------------------------------------------------
4.c# connection MySQL
Program code:
--------------------------------------------------------------------------------

Using Mysqldrivercs;

Establishing a database connection
Mysqlconnection Dbconn;
Dbconn = new Mysqlconnection (newmysqlconnectionstring ("localhost", "MySQL", "Root", "", 3306). asstring);
Dbconn.open ();

Executing query statements
Mysqlcommand Dbcomm;
Dbcomm = new Mysqlcommand ("Select Host,user from User", dbconn);

Reading data
Mysqldatareader dbreader = Dbcomm.executereaderex ();

Display data
Try
{
while (Dbreader.read ())
{
Console.WriteLine ("Host = {0} and User = {1}", dbreader.getstring (0), dbreader.getstring (1));
}
}
Finally
{
Dbreader.close ();
Dbconn.close ();
}

To close a database connection
Dbconn.close ();
--------------------------------------------------------------------------------

5.c# Connect IBM DB2
Program code:
--------------------------------------------------------------------------------

Oledbconnection1.open ();
Open a database connection
Oledbdataadapter1.fill (DataSet1, "address";
Fill in the dataset with the data you have obtained
Datagrid1.databind ();
Binding Data
Oledbconnection1.close ();
Close connection

Increase database data
Add a TextBox with the number of corresponding fields on the Web form, and a button to add the Click Response event code for the key:

This.OleDbInsertCommand1.CommandText = "Insertsintosaddress" (NAME,
EMAIL, age, address) VALUES
(' +textbox1.text+ ', ' "+textbox2.text+" ', ' "+textbox3.text+", ' "+textbox4.text+") ";
OleDbInsertCommand1.Connection.Open ();
Open connection
Oledbinsertcommand1.executenonquery ();
Execute the SQL statement
OleDbInsertCommand1.Connection.Close ();
Close connection
--------------------------------------------------------------------------------

6.c# Connect Sybase
Program code: (OLE DB)
--------------------------------------------------------------------------------

provider=sybase.aseoledbprovider.2;initialcatalog= database name; User id= username; data source= datasource; Extended properties= ""; Server NAME=IP address; Network Protocol=winsock; Server Port address=5000;

Comment

String strconnection= "userid=sa;password=;";
strconnection+= "Initial catalog=northwind; Server=yoursqlserver; ";
strconnection+= "Connect timeout=30";
-------------------
This kind of writing is not good, if the branch must write words can be used StringBuilder, if the database connection is fixed, or write to Webconfig, if you need user input construction, with SqlConnectionStringBuilder better

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.