C #. NET database connection

Source: Internet
Author: User
Tags ibm db2 sybase

1. C # connect to the SQL Server program code: 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 big difference between the mechanism for connecting to the SQL Server database and the mechanism for connecting to Access, 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 for database connection is sa. He also has an alias "uid", so we can also write this sentence 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 sentence can be written as "Database = Northwind ". "Server = YourSQLServer": Use a Server named "YourSQLServer. Its alias is "Data Source", "Address", and "Addr ". If a local database is used and the Instance name is defined, you can enter "Server = (local) \ Instance name". If a remote Server is used) "With the name or IP address of the remote server. "Connect Timeout = 30": the connection Timeout time is 30 seconds. Here, the constructor used to create a connection object is SqlConnection. 2. C # connection Access program code: 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: connecting to the Access database requires importing additional namespaces, so it is essential to have the first two using commands! 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, the Microsoft Jet Engine is used, that 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 "); this saves you a lot of writing! 3. Note that parameters in the connection string must be separated by semicolons. The "OleDbConnection objConnection = newOleDbConnection (strConnection);" clause uses the defined connection string to create a link object. In the future, we will deal with this object for database operations. "ObjConnection. Open ();" is used to Open the connection. Now, the connection to the Access database is complete. 3. C # connect to the Oracle program code: 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 oracleconn = new OracleConnection (ConnectionString ); // create a new connection try {conn. open (); OracleCommand cmd = conn. createCommand (); cmd. commandText = "select * from MyTable"; // write the SQL statement OracleDataReader odr = cmd here. executeReader (); // create an OracleDateReader object while (odr. read () // Read data If odr. if the returned value of Read () is false, {Response. write (odr. getOracleString (1 ). toString (); // output field 1. This number is a field index. How can I use the field name?} odr. close ();} catch (Exception ee) {Response. write (ee. message); // if an error occurs, the output error Message} finally {conn. close (); // Close the connection} 4.C# connection MySQL program code: using MySQLDriverCS; // create 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# connection to IBM DB2 program code: OleDbConnection1.Open (); // open the database connection OleDbDataAdapter1.Fill (dataSet1, "Address"); // enter the obtained data in dataSetDataGrid1.DataBind (); // bind OleDbConnection1.Close (); // close the connection // Add a TextBox and a button to add the number of corresponding fields to the database data on the Web Form, the code for adding a Click RESPONSE event to this button 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 www.2cto. comOleDbInsertCommand1.ExecuteNonQuery (); // execute this SQL statement OleDbInsertCommand1.Connection. close (); // Close the connection 6.C# connect to the SyBase program code: (OleDb) 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.