110,535
社区成员
发帖
与我相关
我的任务
分享
//链接数据库
string myConn = "Data Source = localhost;Initial Catalog = Student ;uid = sa ; pwd = 123";//uid pwd 是SQL数据库的帐户密码
SqlConnection myConnection = new SqlConnection(myConn);
//textBox1是Class_ID ,textBox2是Stu_Name ,textBox3是Mingci
if (textBox1.Text.Trim() == "" ¦ ¦ textBox2.Text.Trim() == "" ¦ ¦ textBox3.Text.Trim() == "" )
{
MessageBox.Show("请输入完整信息");
}
else
{
myConnection.Open();
//判断班级ID是否重复
SqlCommand myCommand = new SqlCommand("select * from Student where Class_ID = '" + textBox1.Text.Trim() + "'", myConnection);
if (null != myCommand.ExecuteScalar())
{
MessageBox.Show("班级ID重复");
}
else
{
string sql = "insert into Student(Class_ID, Stu_Name, Mingci )values(@Class_ID, @Stu_Name, @Mingci)
SqlCommand myCommand = new SqlCommand(sql, myConnection);
myCommand.Parameters.Add(new SqlParameter("@Class_ID", SqlDbType.Int, 4));//你数据库Class_ID设置是什么数据类型就写什么
myCommand.Parameters["@Class_ID"].Value = textBox1.Text.Trim();
myCommand.Parameters.Add(new SqlParameter("@Stu_Name", SqlDbType.NVarChar, 50));//你数据库Stu_Name设置是什么数据类型就写什么
myCommand.Parameters["@Stu_Name"].Value = textBox1.Text.Trim();
myCommand.Parameters.Add(new SqlParameter("@@Mingci", SqlDbType.Int, 4));//你数据库@Mingci设置是什么数据类型就写什么
myCommand.Parameters["@Mingci"].Value = textBox1.Text.Trim();
}
try
{
myCommand.ExecuteNonQuery();
MessageBox.Show("添加成功");
}
catch (SqlException ex)
{
MessageBox.Show("插入数据错误!" + ex.Message.ToString());
}
myConnection.Close();
if( not exists(select class_id from stuinfo where class_id= 3))
begin
insert into stuinfo values(3,'小啥',4);
end