. NET (C #) connection to various database code-Highlights

Source: Internet
Author: User
Tags ibm db2 oracleconnection

1. C # connect to Access
Copy codeThe Code is as follows:
Using System. Data;
Using System. Data. OleDb;
..
String strConnection = "Provider = Microsoft. Jet. OleDb.4.0 ;";
StrConnection + = @ "Data Source = C: BegASPNETNorthwind. mdb ";
OleDbConnection objConnection = new OleDbConnection (strConnection );
..
ObjConnection. Open ();
ObjConnection. Close ();


Explanation:
To connect to the Access database, you need to import additional namespaces. Therefore, the first two using commands are required!
The strConnection variable stores the connection string required to connect to the database. It specifies the data provider to be used and the data source to be used.
"Provider = Microsoft. jet. oleDb.4.0; "is the index data provider. Here we use the Microsoft Jet Engine, which is the Data Engine in Access. asp.net is connected to the Access database.
"Data Source = C: \ BegASPNET \ Northwind. mdb" indicates the location of the Data Source. Its standard format is "Data Source = MyDrive: MyPath \ MyFile. MDB ".
PS:
1. the "@" symbol after "+ =" prevents the "\" symbol in the subsequent string from being parsed as an escape character.
2. If the database file to be connected is in the same directory as the current file, you can use the following method to connect:
StrConnection + = "Data Source = ";
StrConnection + = MapPath ("Northwind. mdb ");
In this way, you can write a lot of things!
3. Note that parameters in the connection string must be separated by semicolons.
"OleDbConnection objConnection = new OleDbConnection (strConnection);" this sentence uses the defined connection string to create a link object. In the future, we will deal with this object for database operations.
"ObjConnection. Open ();" this is used to Open the connection. At this point, the connection to the Access database is complete.

2. C # connect to SQL Server
Copy codeThe Code is as follows:
Using System. Data;
Using System. Data. SqlClient;
..
String strConnection = "user id = sa; password = ;";
StrConnection + = "initial catalog = Northwind; Server = YourSQLServer ;";
StrConnection + = "Connect Timeout = 30 ";
SqlConnection objConnection = new SqlConnection (strConnection );
..
ObjConnection. Open ();
ObjConnection. Close ();


Explanation:
There is no major difference between the mechanism for connecting to the SQL Server database and the Access mechanism, but it only changes the different parameters in the Connection object and Connection string.
First, the namespace used to connect to SQL Server is not "System. Data. OleDb", but "System. Data. SqlClient ".
The second is his connection string. We will introduce them one by one (note: the parameters are separated by semicolons ):
"User id = sa": the authenticated user name used to connect to the database is sa. It also has an alias "uid", so we can also write this statement as "uid = sa ".
"Password =": The verification password for connecting to the database is blank. Its alias is "pwd", so we can write it as "pwd = ".
Note that your SQL Server must have a user name and password set to log on. Otherwise, you cannot log on using this method. if your SQL Server is set to Windows logon, you do not need to use the "user id" and "password" methods to log on here, you need to use "Trusted_Connection = SSPI" to log on.
"Initial catalog = Northwind": the data source used is "Northwind". Its alias is "Database". This statement can be written as "Database = Northwind ".
"Server = YourSQLServer": Use a Server named "YourSQLServer. its alias is "Data Source", "Address", "Addr ". if the local database is used and the Instance name is defined, you can enter "Server = (local) \ Instance name". If it is a remote Server) "Replace with the name or IP address of the remote server.
"Connect Timeout = 30": the connection Timeout is 30 seconds.
Here, the constructor used to create a connection object is SqlConnection.

3. C # connect to Oracle
Copy codeThe Code is as follows:
Using System. Data. OracleClient;
Using System. Data;
// Add a button on the form called Button1, double-click Button1, and enter the following code
Private void button#click (object sender, System. EventArgs e)
{
String ConnectionString = "Data Source = sky; user = system; password = manager;"; // write the connection string
OracleConnection conn = new OracleConnection (ConnectionString); // create a new connection
Try
{
Conn. Open ();
OracleCommand cmd = conn. CreateCommand ();
Cmd. CommandText = "select * from MyTable"; // write an SQL statement here
OracleDataReader odr = cmd. ExecuteReader (); // create an OracleDateReader object
While (odr. Read () // Read data. If odr. Read () returns false, it indicates the end of the record set.
{
Response. Write (odr. GetOracleString (1). ToString (); // output field 1. This number is a field index. How to use the field name remains to be studied.
}
Odr. Close ();
}
Catch (Exception ee)
{
Response. Write (ee. Message); // if an error occurs, the error Message is output.
}
Finally
{
Conn. Close (); // Close the connection
}
}

4. C # connect to MySQL
Copy codeThe Code is as follows:
Using MySQLDriverCS;
// Establish a database connection
MySQLConnection DBConn;
DBConn = new MySQLConnection (new MySQLConnectionString ("localhost", "mysql", "root", "", 3306). AsString );
DBConn. Open ();
// Execute the query statement
MySQLCommand DBComm;
DBComm = new MySQLCommand ("select Host, User from user", DBConn );
// Read 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 ();
}
// Close the database connection
DBConn. Close ();

5. C # connect to IBM DB2
Copy codeThe Code is as follows:
OleDbConnection1.Open ();
// Open the database connection
OleDbDataAdapter1.Fill (dataSet1, "Address ");
// Enter the obtained data in dataSet.
DataGrid1.DataBind ();
// Bind data
OleDbConnection1.Close ();
// Close the connection
// Add database data

Add a TextBox and a button corresponding to the number of fields on the Web Form. The code for adding a Click RESPONSE event to the button is as follows:
Copy codeThe Code is as follows:
This. OleDbInsertCommand1.CommandText = "INSERTsintosADDRESS (NAME,
EMAIL, AGE, ADDRESS) VALUES
('"+ TextBox1.Text +"', '"+ TextBox2.Text +"', '"+ TextBox3.Text +"', '"+ TextBox4.Text + "')";
OleDbInsertCommand1.Connection. Open ();
// Open the connection
OleDbInsertCommand1.ExecuteNonQuery ();
// Execute this SQL statement
OleDbInsertCommand1.Connection. Close ();
// Close the connection

6. C # connect to SyBase
(OleDb)
Copy codeThe Code is as follows:
Provider = Sybase. ASEOLEDBProvider.2; Initial Catalog = database Name; User ID = username; Data Source = Data Source; Extended Properties = ""; Server Name = IP Address; Network Protocol = Winsock; Server Port Address = 5000;

Related Article

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.