关注我 么么哒

【net】数据库实验

  • 作者:smile
  • 学无止境
  • 时间:Tue Jun 16 2020 12:40:21 GMT+0800 (China Standard Time)
  • 237人已阅读
简介 数据库

创建Windows窗体应用程序,要求如下:添加一个窗体Form1,在列表框中显示所有学生的学号、姓名、课程名和分数,并按照学号降序排序,执行界面如图所示。(源代码+运行界面)

数据库为MySQL,用到控件button,listview。

SQL sever 数据库的小伙伴改下引用文件和数据库有关类和连接字符串即可

数据表

idstuIdnameclassNamefenshu
11王华c语言86
21王华数据结构0
32孙丽c语言45
42孙丽数据结构0
53李兵c语言98
6李兵数据结构0
76张军c语言65
86张军数据结构0
9马棋c语言78
108马棋数据结构0

参考代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CreateConn();
            listView1.Columns.Add("", 0, HorizontalAlignment.Left);
            listView1.Columns.Add("学号", 120, HorizontalAlignment.Center);
            listView1.Columns.Add("姓名", 120, HorizontalAlignment.Center);
            listView1.Columns.Add("课程", 120, HorizontalAlignment.Center);
            listView1.Columns.Add("分数", 120, HorizontalAlignment.Center);
        }
        public static MySqlConnection CreateConn()
        {
            string ConString = "server=localhost;User Id=root;password=smile;Database=test;SslMode = none;";
            MySqlConnection conn = new MySqlConnection(ConString);
            try  
                {  
                    conn.Open();
                    Console.WriteLine("已经建立连接"); 
                }  
                catch (MySqlException ex)  
                {
                    Console.WriteLine("建立连接失败!");  
                    Console.WriteLine(ex.Message);  
                }
            return conn;
        }
        protected void button1_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = CreateConn();
            string sqlQuery = "SELECT * FROM fen ORDER BY stuId DESC";
            MySqlCommand comm = new MySqlCommand(sqlQuery, conn);
            MySqlDataReader dr = comm.ExecuteReader();
            while (dr.Read())
            {
                try 
                {
                    ListViewItem lvi = new ListViewItem();
                    lvi.SubItems.Add(dr.GetString("stuId"));
                    lvi.SubItems.Add(dr.GetString("name"));
                    lvi.SubItems.Add(dr.GetString("className"));
                    lvi.SubItems.Add(dr.GetString("fenshu")=="0"?"":dr.GetString("fenshu"));
                    this.listView1.Items.Add(lvi);
                }
                catch { }
            }
            conn.Close();
        }
    }
}

截图

 

文章评论