//链接数据库并添加数据,winform窗口
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient; //很重要使用命名空间
namespace freePractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void butAddCourse_Click(object sender, EventArgs e)
{
//得到文本框的值
string CourseNmae = this.textCourseName.Text;
string CourseByName = this.textByName.Text;
//得到密码文本框的值
string passworld = this.textPassword.Text;
//创建数据库链接字符串
string connString = "server=.;database=StudentMISDB;uid=sa;pwd=123456";
//创建数据库连接对象
SqlConnection con = new SqlConnection(connString);
con.Open();
//要执行的SQL语句
string sql = string.Format("insert into Course values (‘{0}‘,‘{1}‘)", CourseNmae, CourseByName);
//创建SQL命令对象
SqlCommand cmd = new SqlCommand(sql,con);
//判断数据库是否打开状态
if (con.State==ConnectionState.Open)
{
//执行更新回执。返回一个int类型值
int i = cmd.ExecuteNonQuery();
//判断返回值是否位0
if (i==0)
{
MessageBox.Show("修改失败");
}
else
{
MessageBox.Show("修改成功");
}
//
if (con.State==ConnectionState.Open)
{
//关闭数据库链接
con.Close();
}
}
}
}
}