ADO Connect SQL server2008 native database
1. Just connect to the database and do a simple query
1 using(SqlConnection conn =NewSqlConnection ("Data source=127.0.0.1; Initial catalog=mytest; User Id=sa; password=123456"))2 {3 Conn. Open ();4 using(SqlCommand cmd =Conn. CreateCommand ())5 {6 Longi = (Long) cmd. ExecuteScalar ();//Bigint→long7 MessageBox.Show (i.ToString ());8 }9}
2. Can complete the general database connection, to realize the basic function of adding and deleting and checking
1 usingSystem.Windows.Controls;2 usingSystem.Windows.Data;3 usingSystem.Windows.Documents;4 usingSystem.Windows.Input;5 usingSystem.Windows.Media;6 usingSystem.Windows.Media.Imaging;7 usingSystem.Windows.Navigation;8 usingSystem.Windows.Shapes;9 usingSystem.Data.SqlClient;Ten One namespaceADONet Foundation A { - /// <summary> - ///the interactive logic of MainWindow.xaml the /// </summary> - Public Partial classMainwindow:window - { - PublicMainWindow () + { - InitializeComponent (); + } A at Private voidButton1_Click (Objectsender, RoutedEventArgs e) - { - //idisposible - //using (Type D = new ...) - //{.....................} - in //SqlConnection objects for establishing and connecting to a database - //using (SqlConnection conn = new SqlConnection ( to //"Data source=127.0.0.1; Initial catalog=mytest; User Id=sa; password=123456 ")) + //{ - //Conn. Open ();//Open Connection the // //creates an object that sends a command to the database by connecting SqlCommand * //using (SqlCommand cmd = conn. CreateCommand ()) $ // {Panax Notoginseng // //CommandText is the SQL statement to execute - the //Cmd.commandtext = "Insert into t_student (name,age) VALUES (' Yuan Fang ', 2100)"; + //cmd. ExecuteNonQuery ();//Execution A // } the //} + - //ExecuteNonQuery is typically used to perform update, Delete, INSERT statements $ $ using(SqlConnection conn =NewSqlConnection ("Data source=127.0.0.1; Initial catalog=mytest; User Id=sa; password=123456")) - { - Conn. Open (); the using(SqlCommand cmd =Conn. CreateCommand ()) - {Wuyi //cmd.commandtext = "SELECT count (*) from t_student where age<100"; the //int i = (int) cmd. ExecuteScalar (); - //MessageBox.Show (i+ "strip Data"); Wu - //cmd.commandtext = "Select ' AAA '"; About ////executescalar typically used to execute SQL statements with only one row of return values $ //string s = (string) cmd. ExecuteScalar (); - //MessageBox.Show (s); - - //get the value of the self-increment field A //Cmd.commandtext = "INSERT into t_student (name,age) VALUES (' AAA ', 123); select @ @identity"; + //Cmd.commandtext = "INSERT into t_student (name,age) output inserted. Id values (' AAA ', 123) "; the Longi = (Long) cmd. ExecuteScalar ();//Bigint→long - MessageBox.Show (i.ToString ()); $ } the } the the //MessageBox.Show ("execution Complete"); the } - } in}
View Code
The first ADO connection to a SQL Server database