高级语言链接数据库示例

 

上面是代码,使用的是mysql数据库,表是自己建的学生姓名表测试,数据库50例题的数据库

使用了.dataGridView1控件,这控件本来可以直接链接数据库,不用手动写入数据的,但是我的直接链接没做成,只好手动写入数据按照数据库结构一一进行写入

写入中发现没对列进行设置,试图在代码中创建,还是报错,原来是要在窗体里面手动设置好,然后成功。

 

 

using System;
using MySql.Data.MySqlClient;
namespace WinFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            readdatabase();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void readdatabase()
        {
            String connetStr = "server=127.0.0.1;port=3306;user="密码";password=root; database=student;";
            
            MySqlConnection conn = new MySqlConnection(connetStr);
            try
            {
                conn.Open();
                string sql = "select * from student";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                MySqlDataReader reader = cmd.ExecuteReader();//执行ExecuteReader()返回一个MySqlDataReader对象
                
                while (reader.Read())
                {
                    int index = this.dataGridView1.Rows.Add();
                    this.dataGridView1.Rows[index].Cells[0].Value = reader.GetString("s_id");
                    this.dataGridView1.Rows[index].Cells[1].Value = reader.GetString("s_name");
                    this.dataGridView1.Rows[index].Cells[2].Value = reader.GetString("s_birth");
                    this.dataGridView1.Rows[index].Cells[3].Value = reader.GetString("s_sex");


                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值