数据库添加

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ConnSqlForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

//.:为服务期名称 database:要查的那个表 user:数据库的登录名 pwd:为密码

SqlConnection conn = new SqlConnection("server=.;database=snewdata;user=sa;pwd=");
SqlCommand cmd = conn.CreateCommand();

//SQL中的添加语句
cmd.CommandText = "insert into student values(@xuehao,@name,@sex,@birthday)";
cmd.Parameters.Clear();
cmd.Parameters.Add("@xuehao",txtxuehao.Text.Trim());
cmd.Parameters.Add("@name",txtname.Text.Trim());

//判断男女
if (rbtnan.Checked)
{
cmd.Parameters.Add("@sex", "男");
}
else
{
cmd.Parameters.Add("@sex","女");
}
cmd.Parameters.Add("@birthday",dateTimePicker1.Value);

conn.Open();
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
MessageBox.Show("执行成功,受影响行数为:" + count.ToString());
}
else
{
MessageBox.Show("执行失败!");
}
conn.Close();//每次运行完关闭一下
}
}
}

posted @ 2015-01-26 11:21  巽坤  阅读(120)  评论(0编辑  收藏  举报