winform —— 连接数据库SQL Server 2008

using System.Data.SqlClient;命名空间
sqlconnection:数据连接类
sqlcommand:数据库操作类
sqldatareader:读取

winform  —— 连接数据库SQL Server 2008

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string username = textBox1.Text;
string upass = textBox2.Text; //第一步:连接到数据库
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=");
conn.Open();
//第二步:写执行语句
SqlCommand cmd = conn.CreateCommand();//通过conn创建sqlcommand对象
cmd.CommandText = "select *from users where uname='"+username+"' and upass='"+upass+"'";
SqlDataReader dr = cmd.ExecuteReader();//执行查询,返回sqldatareader对象
if (dr.Read())
{
MessageBox.Show("登陆成功!");
}
else
{
MessageBox.Show("登陆失败!");
} conn.Close();
} private void button2_Click(object sender, EventArgs e)
{
//添加数据到数据库
string username = textBox1.Text;
string upass = textBox2.Text; //第一步:连接到数据库
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into users values('"+username+"','"+upass+"')";
int count= cmd.ExecuteNonQuery();//增删改
if (count > )
{
MessageBox.Show("添加成功!");
}
else
{
MessageBox.Show("添加失败!");
}
conn.Close();
} private void button3_Click(object sender, EventArgs e)
{
string code = textBox3.Text;
string uname = textBox1.Text;
string upass = textBox2.Text;
//第一步:连接到数据库
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "update users set uname='"+uname+"',upass='"+upass+"' where code="+code;
int count=cmd.ExecuteNonQuery();
if (count > )
{
MessageBox.Show("修改成功!");
}
else
{
MessageBox.Show("修改失败!");
}
conn.Close();
} private void button4_Click(object sender, EventArgs e)
{
string code = textBox3.Text;
SqlConnection conn = new SqlConnection("server=.;database=data1220;user=sa;pwd=");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "delete from users where code="+code;
cmd.ExecuteNonQuery();
conn.Close();
} private void Form1_Load(object sender, EventArgs e)
{ }
}
}
上一篇:Linux下执行Java程序报错


下一篇:如何使用加多宝(jdb)在linux下调试Java程序