您的位置:首页 > 数据库 > MySQL

第四次作业:MySQL数据库及C#操作MySQL数据库

2015-05-24 20:52 309 查看
物联1121 201211672132 姚硕云
一、功能简介
目标2:C#操作sql server数据库

(1)连接作业1中建立的数据库中的相关的表(table),显示在DataGridView控件中

(2)C#语言编程实现数据库的插入、删除、修改某一条或若干条记录
二、源代码
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.Threading.Tasks;
using System.Windows.Forms;

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

private void Form1_Load(object sender, EventArgs e)
{
dataOperate("select * from product");
}

private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text=="" || textBox1.Text.Trim()=="")
{
MessageBox.Show("请输入正确的SQL语句");
}
try
{
string sql = textBox1.Text.ToString();
dataOperate(sql);
}
catch (Exception exp)
{ }
}

private void dataOperate(string sql)
{
DataSet ds = new DataSet();
string consqlserver = "Data Source=.;Initial Catalog=warehouse;Integrated Security=True;";
SqlConnection con = new SqlConnection(consqlserver);
SqlCommand com = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(com);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
dataGridView1.DataSource = ds.Tables[0];
}
}
catch (Exception msg)
{
throw new Exception(msg.ToString());
}
finally
{
con.Close();
con.Dispose();
da.Dispose();
}
}

private void button2_Click(object sender, EventArgs e)
{
dataOperate("select * from product");
}
}
}
三、运行结果
(1)主界面




(2)选择记录




(3)插入新记录




(4)删除记录




(5)更新记录




四、心得与体会
每完成一次编程作业,都会有收获,不管大小,总会鞭策着自己继续往更远的路走下去……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: