Sei sulla pagina 1di 2

ADO .

Net SQL Connection


using System; using System.Data; using System.Data.SqlClient; class MainClass { static void Main(string[] args) { SqlConnection MyConnection = new SqlConnection("Data Source=(local);Initial Catalog =sun;User ID=sa;Password=sa"); MyConnection.Open(); Console.WriteLine("connected "); Console.Read(); } }
using System; using System.Data; using System.Data.SqlClient; /// <summary> /// Demonstrates how to work with SqlConnection objects /// </summary> class SqlConnectionDemo { static void Main() { // 1. Instantiate the connection SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=sun;Integrated Security=SSPI"); SqlDataReader rdr = null; try {

// 2. Open the connection conn.Open();

// 3. Pass the connection to a command object SqlCommand cmd = new SqlCommand("select cname from customers", conn); // // 4. Use the connection // // get query results rdr = cmd.ExecuteReader();

} finally { // close the reader if (rdr != null) { rdr.Close(); }

// print the CustomerID of each record while (rdr.Read()) { Console.WriteLine(rdr[0]); }

} }

} Console.Read();

// 5. Close the connection if (conn != null) { conn.Close(); }

using System; using System.Data; using System.Data.SqlClient; class MainClass { static void Main(string[] args) { string connString = "Data Source=(local);Initial Catalog =sun;User ID=sa;Password=sa"; SqlConnection conn = new SqlConnection(connString); try { conn.Open(); Console.WriteLine("Connection opened."); } catch (SqlException e) { Console.WriteLine("Error: " + e); } finally { conn.Close(); Console.WriteLine("Connection closed."); } Console.Read();

} }

Potrebbero piacerti anche