首页 > 数据库 >WPF access mysql and pass data from datagrid to mysql

WPF access mysql and pass data from datagrid to mysql

时间:2024-09-01 16:15:49浏览次数:13  
标签:access set get System datagrid mysql using null public

//sql
drop database if exists mydb;
create database mydb;
use mydb;
drop table if exists mt;
create table mt
(id int auto_increment primary key,
name varchar(50) not null default '',
isbn varchar(50) not null default '',
author varchar(50) not null default '',
comment varchar(50) not null default '',
content varchar(50) not null default '',
summary varbinary(50) not null default '',
title varchar(50) not null default '',
topic varchar(50) not null default '',
Congest blob not null
);

 

 

//<Window x:Class="WpfApp319.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp319"
        mc:Ignorable="d" WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="{x:Type Button}" x:Key="btnStyle">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="Width" Value="150"/>
        </Style>
    </Window.Resources>
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="New" Command="{Binding NewCmd}" Style="{StaticResource  btnStyle}"/>
            <GridSplitter/>
            <Button Content="Save" Command="{Binding SaveCmd}" Style="{StaticResource  btnStyle}"/>
            <GridSplitter/>
            <Button Content="Load" Command="{Binding LoadCmd}" Style="{StaticResource  btnStyle}"/>
            <GridSplitter/>
            <Button Content="Import" Command="{Binding ImportCmd}" Style="{StaticResource  btnStyle}"/>
            <GridSplitter/>
            <Button Content="Export" Command="{Binding ExportCmd}" Style="{StaticResource  btnStyle}"/>
            <GridSplitter/>
        </ToolBar>
        <DataGrid Grid.Row="1" 
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  AutoGenerateColumns="False" CanUserAddRows="False" 
                  EnableColumnVirtualization="True"
                  EnableRowVirtualization="True"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Author" Binding="{Binding Author}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Comment" Binding="{Binding Comment}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Content" Binding="{Binding Content}" IsReadOnly="True"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Summary" Binding="{Binding Summary}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}" IsReadOnly="True"/>
                <DataGridTextColumn Header="Topic" Binding="{Binding Topic}" IsReadOnly="True"/>
                <DataGridTemplateColumn Header="ImgUrl" IsReadOnly="True">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding ImgUrl}" Width="200" Height="500"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace WpfApp319
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //DBHelper.InsertInto("");
        }
    }

    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitCommands();
            InitData();
        }

        private void InitData()
        {
            imgsList = System.IO.Directory.GetFiles(@"../../Images")?.ToList();
            imgsCount = imgsList.Count;
        }

        private void InitCommands()
        {
            NewCmd = new DelCmd(NewCmdExecuted);
            SaveCmd = new DelCmd(SaveCmdExecuted);
            LoadCmd = new DelCmd(LoadCmdExecuted);
            ExportCmd = new DelCmd(ExportCmdExecuted);
            ImportCmd = new DelCmd(ImportCmdExecuted);
        }

        private void SaveCmdExecuted(object obj)
        {
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.Append("insert into mt(author,name,isbn,comment,content,summary,title,topic,imgurl,congest) values ");
            if(BooksCollection!=null && BooksCollection.Any())
            {
                int booksCnt = BooksCollection.Count;
                for(int i=0;i<booksCnt;i++)
                {
                    var bk= BooksCollection[i];
                    sqlBuilder.Append($"('{bk.Author}','{bk.Name}','{bk.ISBN}','{bk.Comment}','{bk.Content}'," +
                        $"'{bk.Summary}','{bk.Title}','{bk.Topic}','{bk.ImgUrl}','{bk.ToString()}'),");
                }
            }

            string sqlStr = sqlBuilder.ToString().Substring(0,sqlBuilder.Length - 1);
            int insertedResult = DBHelper.InsertInto(sqlStr);
            MessageBox.Show($"Inserted :{insertedResult} successfully!");
        }

        private void ImportCmdExecuted(object obj)
        {

        }

        private void ExportCmdExecuted(object obj)
        {

        }

        private void LoadCmdExecuted(object obj)
        {

        }

        private void NewCmdExecuted(object obj)
        {
            BooksCollection = new ObservableCollection<Book>();
            for (int i = 1; i <= 100000; i++)
            {
                BooksCollection.Add(new Book()
                {
                    Id = i,
                    Name = $"Name_{i}",
                    Author = $"Author_{i}",
                    ISBN = $"ISBN_{i}",
                    Comment = $"Comment_{i}",
                    Content = $"Content_{i}",
                    Summary = $"Summary_{i}",
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}",
                    ImgUrl = $"{imgsList[i % imgsCount]}",
                    Congest = this.ToString()
                });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        #region Properties

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                if (value != booksCollection)
                {
                    booksCollection = value;
                    OnPropertyChanged(nameof(BooksCollection));
                }
            }
        }

        private List<string> imgsList;
        private int imgsCount = 0;

        #endregion

        #region Commands
        public DelCmd NewCmd { get; set; }

        public DelCmd SaveCmd { get; set; }

        public DelCmd LoadCmd { get; set; }

        public DelCmd ExportCmd { get; set; }

        public DelCmd ImportCmd { get; set; }

        #endregion

    }

    public class DBHelper
    {
        static string connStr = @"Server=localhost;database=mydb;user=usernamevalue;password=passwordvalue;";
        static MySqlConnection conn { get; set; }

        static DBHelper()
        {
            conn = new MySqlConnection(connStr);
            conn.Open();
        }


        public static int InsertInto(string sqlStr)
        {
            if (conn.State == System.Data.ConnectionState.Closed)
            {
                conn.Open();
            }

            using (MySqlCommand cmd = new MySqlCommand(sqlStr, conn))
            {
                int insertedRows = cmd.ExecuteNonQuery();
                return insertedRows;
            }
        }


        ~DBHelper()
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
                conn = null;
            }
            else if (conn != null)
            {
                conn = null;
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string Author { get; set; }

        public string Comment { get; set; }

        public string Content { get; set; }

        public string Name { get; set; }

        public string ISBN { get; set; }

        public string Summary { get; set; }

        public string Title { get; set; }

        public string Topic { get; set; }

        public string Congest { get; set; }

        public string ImgUrl { get; set; }

        public override string ToString()
        {
            return $"{Id},{Author},{Comment},{Content},{Name},{ISBN},{Summary},{Title},{Topic}";
        }
    }

    public class DelCmd : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;

        public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public DelCmd(Action<object> executeValue) : this(executeValue, null)
        {
        }


        public bool CanExecute(object parameter)
        {
            if (parameter == null)
            {
                return true;
            }
            return canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
    }
}

 

 

 

 

 

标签:access,set,get,System,datagrid,mysql,using,null,public
From: https://www.cnblogs.com/Fred1987/p/18391372

相关文章

  • python读取txt文本文件-批量更改mysql数据库中一批用户的用户名的python脚本保存及转
    一、python读取txt文本文件-批量更改mysql数据库中一批用户的用户名的python脚本保存    做一个简单的事:使用python读取一个txt文件,里面存储着N行用户id,需要一行行读取后再读取另一个存储用户昵称的txt文件,判断昵称是否有重复,如果没有重复就将数据库中的当前uid用户的昵称......
  • 基于Java+SpringBoot+Mysql在线众筹系统功能设计与实现一
    一、前言介绍:1.1项目摘要随着互联网的普及和人们消费观念的转变,众筹作为一种创新的融资方式,逐渐受到社会各界的关注和青睐。它打破了传统融资模式的限制,为初创企业、艺术家、公益项目等提供了更为灵活和便捷的融资渠道。因此,开发众筹系统旨在满足这一市场需求,促进创新项......
  • MySQL中日期和时间戳的转换:字符到DATE和TIMESTAMP的相互转换
    在MySQL中,经常需要在DATE、TIMESTAMP和字符串之间进行相互转换。以下是一些常见的转换方法:1.字符串到日期/时间类型字符串转DATE:使用STR_TO_DATE()函数将字符串转换为DATE类型。你需要提供字符串的格式。SELECTSTR_TO_DATE('2024-08-24','%Y-%m-%d')ASmy_......
  • mysqlbackup处理过程说明
    InnoDBdatafiles,redolog,binarylog,和relaylogfiles(除了正在使用的log文件)被拷贝到备份,这个期间数据库服务可以想平常一样使用innodb的表结构和数据可能在这个期间发生变化,所以下面的步骤就是确保这些变化被捕捉到备份中一个backuplock会被应用到服务器实例上,他会阻塞DD......
  • MySQL的索引原理及使用
    MySQL中的索引模型Mysql中的索引使用的数据结构一般为搜索树,这里的搜索树,一般使用B树,这里补一下数据结构中的B树结构;说B树之前,先顺一个前置的知识点,平衡二叉树;平衡二叉树二叉树应该都不陌生,大学数据结构的基本入门,二叉排序树是基于二叉树上多了个“有序”的概念,简单来说,即左<......
  • MySQL的索引原理及使用
    索引模型(基础数据结构)索引模型:哈希表、有序数组、搜索树,这里的模型是指索引的底层实现的基本数据结构,Mysql中不同的引擎对于索引的实现结构说的即是索引模型。 有序数组有序数组这个在数据结构中是最基础的结构,也是最简单的,对比理解的话就是我们编程中常用的数组、链表,它......
  • PHP 预定义类 ArrayAccess接口的使用
    1何为预定义php中的预定义是指的是被视为全局可用的内置常量、变量、函数、类、接口,这些内容不需要特别的引入或申明,本身就存在于php语言中。php预定义类目录:https://www.php.net/manual/zh/reserved.classes.php2 ArrayAccess接口简介ArrayAccess接口可以让你在操纵对象......
  • 可重复读隔离级别真的完全解决不可重复读问题了吗?读已提交隔离级别能避免不可重复读问
    一文带你搞懂MySQL事务的各个疑惑,不要再在脑子里一团浆糊啦!!事务的四大特性MySQL的三种日志事务的原子性是如何保证的?事务的隔离性是如何保证的?事务的持久性是如何保证的?数据库事务的隔离级别各隔离级别都各自解决了什么并发问题?什么是MVCC?读已提交和可重复读隔离级别实......
  • 20240904_070346 mysql 存储过程 认识
    什么是存储过程存储过程的特点......
  • 20240904_080346 mysql 存储过程 创建与使用存储过程
    存储过程的使用修改结束符号将默认的句子结束符号由;改为$号的写法创建存储过程调用存储过程......