一:连接。
string sqlconn = "server=主机名;database=数据名;integrated security=true" //integrated security 当为true时,将使用当前的Windows帐户凭据进行身份验证。
string sqlconn = "server=主机名;database=数据名;uid=用户ID;pwd=密码;" //integrated security 当为false时,将在连接中指定用户ID和密码。 string sqlcomm = "select * from student_info";//sql语句 SqlConnection conn = new SqlConnection(sqlconn); conn.Open(); SqlCommand comm = new SqlCommand(sqlcom, conn);
二:通过TextBox控件添加。
string sno = snoTextBox.Text; string name = nameTextBox.Text; string sex = sexTextBox.Text; nt age = Convert.ToInt32(ageTextBox.Text); string sqlconn = "server=.;database=student;integrated security=true"; string sqlcomm = "insert into student_info values('"+sno+"','"+name+"',"+age+",'"+sex+"')"; SqlConnection conn = new SqlConnection(sqlconn); conn.Open(); SqlCommand comm = new SqlCommand(sqlcomm, conn); comm.ExecuteNonQuery(); conn.Close();
三:删除。
string sno = snoTextBox.Text; string sqlconn = "server=.;database=student;integrated security=true"; string sqlcomm = "delete from student_info where stu_sno=" + sno; SqlConnection conn = new SqlConnection(sqlconn); conn.Open(); SqlCommand comm = new SqlCommand(sqlcomm, conn); comm.ExecuteNonQuery(); conn.Open();
三:更新。
string sno = snoTextBox.Text; string name = nameTextBox.Text; string sex = sexTextBox.Text; int age = Convert.ToInt32(ageTextBox.Text); string sqlconn = "server=.;database=student;integrated security=true"; string sqlcomm = "update student_info set stu_sno='"+sno+"',stu_name='"+name+"',stu_sex='"+sex+"',stu_age="+age+" where stu_sno=" + sno; SqlConnection conn = new SqlConnection(sqlconn); conn.Open(); SqlCommand comm = new SqlCommand(sqlcomm, conn); comm.ExecuteNonQuery(); conn.Close();
上面的代码是全部数据一块更新的,也可以只更新某些数据项。