c# 向mysql插入数据_在C#中将记录插入MySQL数据库

在上一教程(如何在C#中与MySQL数据库连接?)中,我们学习了如何在C#中与MySQL数据库建立连接。在这里,在本教程中,我们将学习如何在C#中的MySQL数据库中插入记录?

在这里,我们正在创建一个Windows应用程序,它将学生记录存储到数据库中。因此,首先,我们将使用“显示数据库”选择数据库,然后更改/使用“使用mysqltest”数据库,这里“使用mysqltest”是数据库名称。

b4fd08d403bb13e4d294d7576fde62bf.png

ad6c8609747b6f3c48f00b623462de37.png

现在,我们将使用“创建表”命令创建一个学生表,并在其中插入记录。

6988fb91a9a0a5a1952c43c39203e596.png

在上表中,我们创建了以下几列,rollno用于存储学生的卷号。

name它用于存储学生的姓名。

age用于存储学生的年龄。

class它用于存储学生在学校的班级。

fee用于存储费用金额

现在,我们将开发一个将学生信息存储到数据库中的应用程序。

C#应用程序将学生信息存储到MySQL数据库中fba98659cf55c32c591f11d2f5f3ecfd.png

在上述应用程序中,我们更改了以下属性,Form

Name:frmStuInfo

Text:Student Information    Label1

Text:Roll Number    Label2

Text:Name    Label3

Text:Age    Label4

Text:Class    Label5

Text:Fee    Button1

Text :Save To Database

用C#代码将记录插入MySQL数据库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 MySql.Data.MySqlClient;

namespace Insertion

{

public partial class frmStuInfo : Form

{

public frmStuInfo()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

MySqlConnection conn = new MySqlConnection("server=localhost;database=mysqltest;uid=root;pwd=root");

MySqlCommand cmd = null;

string cmdString = "";

conn.Open();

cmdString = "insert into student values(" + textBox1.Text + ",'" + textBox2.Text + "'," + textBox3.Text + ",'" + textBox4.Text + "'," + textBox5.Text + ")";

cmd = new MySqlCommand(cmdString, conn);

cmd.ExecuteNonQuery();

conn.Close();

MessageBox.Show("Data Stored Successfully");

}

}

}

现在,在上述源代码中,我们包括用于MySQL数据库连接的命名空间:“ MySql.Data.MySqlClient”。

我们使用了两个类MySqlConnection和MySqlCommand,在这里我们准备了连接数据库的连接字符串。"server=localhost;database=mysqltest;uid=root;pwd=root"

我们准备了带有插入文本框值的insert命令。并执行使用该命令ExecuteNonQuery()的方法的的MySqlCommand类。最后,关闭连接并使用MessageBox显示适当的消息。

现在看一下应用程序的输出,ef7b169f1942dda41c381d0767f987fe.png

在上面的应用程序中,我们填写了有关学生的信息,然后单击命令按钮,将给定的信息存储到数据库中。现在,我们将使用MySQL提示符将信息检入MYSQL数据库。19103559208fc89873399c431d786706.png

在这里,我们可以看到应用程序提供的信息已正确保存到数据库中。

猜你喜欢

转载自blog.csdn.net/weixin_39621819/article/details/113892331