C# How To Insert Data To MySQL Using C#?

To insert data to MySQL using C# program, we need to create a connection with the database first. After that, we can create a transaction object and execute the insert method to insert data into the table.

mysql insert into select transaction c#

By Plain PorpoisePlain Porpoise on Dec 21, 2020
const string InsertStatement1 = @"INSERT INTO tbl_inv (cname, date, duedate, subtotal, vat, total) 
    VALUES (@cname, @date, @duedate, @subtotal, @vat, @total);";
const string InsertStatement2 = @"INSERT INTO tbl_line (invno, pname, qty, unitprice, amount) 
    VALUES (@invno, @pname, @qty, @unitprice, @amount);";

using (MySqlTransaction sqlTrans = cn.BeginTransaction())
using (MySqlCommand sqlCommand = new MySqlCommand(InsertStatement1, cn, sqlTrans))
    sqlCommand.Parameters.Add("@cname", comboBox1.Text);
    sqlCommand.Parameters.Add("@date", dateTimePicker1.Value.ToString("yyyy-MM-dd"));
    sqlCommand.Parameters.Add("@duedate", dateTimePicker2.Value.ToString("yyyy-MM-dd"));
    sqlCommand.Parameters.Add("@subtotal", textBox6.Text);
    sqlCommand.Parameters.Add("@vat", textBox7.Text);
    sqlCommand.Parameters.Add("@total", textBox9.Text);

    sqlCommand.CommandText = "SELECT LAST_INSERT_ID();";
    var o = sqlCommand.ExecuteScalar();
    if (o is Int64)
        var id = (Int64)o;
        foreach (DataGridViewRow row in mg2.Rows)
            sqlCommand.Parameters.AddWithValue("@invno", id);
            sqlCommand.Parameters.AddWithValue("@pname", row.Cells[1].Value);
            sqlCommand.Parameters.AddWithValue("@qty", row.Cells[2].Value);
            sqlCommand.Parameters.AddWithValue("@unitprice", row.Cells[3].Value);
            sqlCommand.Parameters.AddWithValue("@amount", row.Cells[4].Value);
            sqlCommand.CommandText = InsertStatement2;

Source: stackoverflow.com

Add Comment


This code will inserts data from C# application to MySQL database using .NET Framework with an example.

SQL answers related to "mysql insert into select transaction c#"

View All SQL queries

SQL queries related to "mysql insert into select transaction c#"

mysql insert into select transaction c# INSERT INTO GBP Plus(Index Change) VALUES( AND((SELECT NUMINDEX FROM GBP WHERE ID>ID-1) - (SELECT NUMINDEX FROM GBP WHERE ID=ID )) mysql insert into select with recursive sql server split string and insert into table select insert into select * sql server sql select data from one database and insert into a different database insert into select sql Postgres INSERT INTO select from table insert into select oracle mysql insert multiple rows based on select transaction database with php transaction php transaction database php dbms transaction tutorialspoint Hotspot,Double click,Move to transaction transaction and commit trong sql server sql begin transaction insert into in DBT prehook ext:sql intext:"INSERT INTO" intext:@gmail.com intext:password pop sql insert value into can't connect to local mysql server through socket '/var/lib/mysql/mysql.sock' deny select insert update delete sql mysql insert on dupèlicate mySql insert row insert mysql bulk insert mysql from list of tuples how to insert multiple rows in mysql using stored procedure mysql insert mysqli How to insert date in mysql select into select in select sql mysql load csv into table mysql write into table how to automate data parsing with version and primary key into mysql using python mysql select else if SELECT User,Host FROM mysql.user; select tables with name like mysql select case mysql mysql select and count left join mysql select update same table select where mysql c# add a textbox in mysql select c# select Mysql mysql select row max date como hacer un select entre fechas mysql mysql create table from select statement mysql select bottom 10 rows MySQL SELECT mysql select count if contains mysql select all columns and specific fields as mysql query select more columns mysql select date from datetime mysql select as select database in mysql MySQL select from where multiple conditions select top mysql get the mysql table columns data type mysql ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package sql insert inserted id pl sql trigger determine if insert or update or delete sqlite insert row return insert results in POSTGRESQL insert postgres sql insert from excel sql multiple insert postgres insert in to table sql oracle insert single quote in string how to insert multiple rows in ssms impala insert multiple rows how to get the primary key after an insert h2 mysl like insert a variable sql insert tuple Fatal error: Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1 in t_sql insert one insert many values postgresql Msg 8164, Level 16, State 1, Procedure getSalaryMonth, Line 31 [Batch Start Line 13] An INSERT EXEC statement cannot be nested. httpwebclient request and insert to sql server trigger before insert sqlite insert Check if value exisits update or insert sQL insert date in sql insert if not exists sql load csv files into postgres db sqlalchemy CONVERT time string into 12 hours in sql convert excel into sqllite db using python select index table oracle sql select except null could not find driver (SQL: select * from information_schema.tables where table_schema = pics and table_name = migrations and table_type = 'BASE TABLE') select if then postgresql sql update from select illuminate database queryexception could not find driver (sql select * from t-sql update from select sql select select current_timestamp - interval '3 days'; postgresql psycopg2 select single value update from select join sql select inner join example sql server select rows by distinct column update from select oracle sql select rows with simlar names sqlserver: can we select from comma seperated string variable value sql select without reference General error: 11 database disk image is malformed (SQL: select * from sqlite_master where type = 'table' and name = migrations) sql empty select sql select column name like from multiple tables Sql select by content lenght select minimum value sql select 1 from orders sql select without column name sql select min oracle sql select from multiple tables function pl sql with select select all domains of database firbird raven ql select count criteria builder select subset of column The SELECT permission has not been granted on 'sys.sql_logins' for the 'master' database. You must be a member of the 'loginmanager' role to access this system view. update from select delete from select postgresql SELECT FROM select from 3 tables one is empty select distinct on 2 columns update from select postgresql oracle select top 100 select from where install mysql from ubuntu cast string to datetime mysql mysql CURRENT_TIMESTAMP() mysql date format unix timestamp create table mysql how ot change name of column mysql bulk kill mysql processlist how to check username in mysql command line how to get current mysql version how to create a variable in mysql set utf8mb4 mysql tables update left join mysql mysql see users and passwords mysql show variables update part of a string in mysql mysql delete row django mysql settings mysql import gz mysql version check cmd mysql date between two dates how to update an attribute in MySQL group by mysql and concatenate string how to show all users in mysql how to alter table column name in mysql mysql url mysql remote connection command line mysql install windows 10 mysql timestamp to date mysql get last day of month mysql last day of next month change mysql password from command line mysql check date range login mysql update substring in mysql show all users in mysql drop table in mysql mysql number format update mysql mysql string length mysql format date mysql to date create user mysql debian 10 grant revoke privileges to mysql username how to run mysql in git bash ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client vs code mysql' is not recognized as an internal or external command, set database timezone mysql input in mysql mysql debezium set id count mysql create temporary table in mysql ubuntu stop mysql from starting on boot mysql get longest string in column mysql run sql file mysql count vs sum mysql update query host 127.0 0.1 is not allowed to connect to this mysql server mysql backup database how to run mysql on terminal mac create a table with an id in mysql mysql create stored procedure ubuntu reset mysql root password alter table add column and foreign key mysql mysql dump specific tables mysql pivot how to change mysql root password in windows 10 date conversion in mysql column limit offset order by mysql mysql workbench tutorial add column mysql with foreign key mysql if else mysql connector/python query example mysql version group_concat mysql

Browse Other Code Languages