Private voidForm1_Load (Objectsender, EventArgs e) { stringSqlstr ="server=localhost;database=my";//Create a database connection string; I do not add a user name and password. conn =NewSqlConnection (SQLSTR);//instantiating a SqlConnection database connection objectConn. Open ();//Open a database connection if(Conn. state = = ConnectionState.Open)//determine if the connection is open{Label1. Text="SQL Server database connection open! "; } } Private voidButton1_Click (Objectsender, EventArgs e) { //define SQL statements that add data stringstrSQL ="INSERT INTO S (sno,age) VALUES ('"+ TextBox1.Text +"',"+ Convert.todecimal (TextBox2.Text) +")"; //String strSQL = "INSERT into S (sno,sn,age,sex,dept) VALUES (' S3 ', ' Cao Shu ', 2, ' female ', ' chemistry ')";SqlCommand Comm =NewSqlCommand (strSQL, conn);//instantiating a SqlCommand object if(Conn. state = = connectionstate.closed)//determine if the connection is closed{Conn. Open ();//Open a database connection } //determines whether the parameter returned by the ExecuteNonQuery method is greater than 0, greater than 0 indicates a successful addition if(Convert.ToInt32 (Comm. ExecuteNonQuery ()) >0) {label3. Text="Add success! "; } Else{label3. Text="Add failed! "; } conn. Close ();//To close a database connection if(Conn. state = = connectionstate.closed)//determine if the connection is closed{MessageBox.Show ("database to close"); } } }}//I just copied a private void Button1_Click (object sender, EventArgs e) {...} from somewhere else. function code, and then directly from the Toolbox//Drag a Button1 button, but I click this button do not execute, because the event of this button is not driven, click Button1 This code will not be executed! //Be sure to remember to copy only the contents of the function, then double-click the Button1 button to automatically generate the function frame, and then paste the code in it!
How to connect a sql2000 database