using(SqlConnection conn=new SqlConnection(strconnection)) //创建数据库连接,使用using,会自动释放 { conn.Open(); //打开连接 string sql = "insert into newstudent values (@name,@sex,@address,@phone)"; //定义sql语句,@开头为参数 SqlCommand cmd = new SqlCommand(sql, conn); //实例化sqlcommand,以备传输sql语句到对应的数据库连接中 SqlParameter[] ps ={ //定义数据,为参数赋值 new SqlParameter("@name",txtName.Text.Trim()), new SqlParameter("@sex",txtSex.Text.Trim()), new SqlParameter("@address",txtAddress.Text.Trim()), new SqlParameter("@phone",txtPhone.Text.Trim()) }; cmd.Parameters.AddRange(ps); cmd.ExecuteNonQuery();//执行sql语句 MessageBox.Show("保存成功"); }
时间: 2024-10-10 16:15:04