C#/MySql 5: Insert into table
Written by: maffelu , 2009-04-17 07:29:18
commandLine = @"INSERT INTO mycontacts(
name,
age
)
VALUES
(
'Bob',
'49'
);";
cmd.CommandText = commandLine;
cmd.ExecuteNonQuery();
commandLine = @"INSERT INTO mycontacts(
name,
age
)
VALUES
(
@name,
@age
);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("@name", inputName);
cmd.Parameters.AddWithValue("@age", inputAge);
cmd.ExecuteNonQuery();
using System;
using MySql.Data.MySqlClient;
namespace MorkConsTest
{
class Program
{
static void Main(string[] args)
{
MySqlConnection connect;
MySqlCommand cmd;
string connectionLine;
string commandLine;
//========================CONNECTION PART==========================
//Create a connection string
connectionLine = "Data source=localhost;UserId=root;Password=dog;";
//Instantiate the MySqlConnection class, constructor takes one connectionstring
connect = new MySqlConnection(connectionLine);
//Instantiate the MySqlCommand class
cmd = new MySqlCommand();
try
{
//Create a connection
cmd.Connection = connect;
//Open the connection
cmd.Connection.Open();
Console.WriteLine("Connection opened.");
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
//=========================CREATE DATABASE============================
//Create a query
commandLine = "CREATE DATABASE mydb;";
//Set the command query
cmd.CommandText = commandLine;
try
{
//Execute the command query
cmd.ExecuteNonQuery();
Console.WriteLine("Database created.");
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
//Close the connection
cmd.Connection.Close();
Console.WriteLine("Connection closed.");
}
//==============================CREATE TABLE===============================
//Alter the connection string to now select a database
connectionLine = "Data source=localhost;Database=mydb;UserId=root;Password=dog;";
connect = new MySqlConnection(connectionLine);
commandLine = @"CREATE TABLE myContacts
(
name VARCHAR(150),
age INT(3)
)";
Console.WriteLine("Attempting to create table...");
try
{
//Enter the query to the CommandText
cmd.CommandText = commandLine;
//Create and open the connection previously made
cmd.Connection = connect;
cmd.Connection.Open();
Console.WriteLine("Connection opened...");
//Execute the CommandText
cmd.ExecuteNonQuery();
Console.WriteLine("Table created!");
//Always remember to close the door after you leave :)
cmd.Connection.Close();
Console.WriteLine("Connection closed...");
}
catch (MySqlException ex)
{
//It fails!
Console.WriteLine("Operation failed, table was not created...");
Console.WriteLine(ex.ToString());
}
//================INPUT IN TABLE============================
string inputName;
string inputAge;
string inputControl;
bool ender = false;
commandLine = @"INSERT INTO mycontacts(
name,
age
)
VALUES
(
@name,
@age
);";
do
{
Console.Clear();
Console.Write("Enter a friends name: ");
inputName = Console.ReadLine();
Console.Write("Enter that friends age: ");
inputAge = Console.ReadLine();
//Set the command text
cmd.CommandText = commandLine;
//Set the parameters
cmd.Parameters.AddWithValue("@name", inputName);
cmd.Parameters.AddWithValue("@age", inputAge);
try
{
//Open a connection
cmd.Connection.Open();
//Execute the command
cmd.ExecuteNonQuery();
//Close the connection
cmd.Connection.Close();
}
catch (MySqlException ex)
{
Console.WriteLine("Error: \r\n" ex.ToString());
}
//Clear parameters
cmd.Parameters.Clear();
Console.Write("If you want to quit enter \"quit\": ");
inputControl = Console.ReadLine();
if (inputControl == "quit")
{
ender = true;
}
} while (!ender);
Console.Read();
}
}
}
There are 6 comments on this article.
sunil
2011-06-28 10:51:17
can u send me basic code for inserting values in atable in c##
sunil
2011-06-28 11:15:54
can u send me basic code for inserting values in atable in c##
maffelu
2011-06-29 12:25:08
Sunil: No
I don't give away code more than what you can find in these articles.
Given the code above it shouldn't be hard to come up with a way to insert values into a table. It's actually being done in this code.
kerm123
2011-08-13 17:14:32
first of all... thanks for the post... however, i find whenever i google a programing question that leads me to a forum guys are SUCH PRICKS to dudes that need help in many cases.... why is this???? i.e. "i don't give away code more than what you can find in these articles" etc... i am an engineer who happens to need to put my programmer hat on at the moment so i've been looking around to have questions answered... it's almost as if you guys think bringing other up to speed decreases your value as a programmer! i don't know... maybe it's just me...
btw this is a light example of what i'm talking about... if you look other places you see a lot of condescending answers to those looking for help... grow up guys!!!
maffelu
2011-08-15 00:46:09
kerm123:
I know what you mean actually, but with the "you haz deh code???"-like comments like the one above I can't give the code away because that would not be helping, that would be doing somebody elses work.
I am happy to help, but there is a difference between giving someone the basis of understanding and giving someone all the code they need. In the latter they won't learn anything.
If you want someone to just hand you code, hire a consultant, if you want help, ask and people will explain, but not do your work for you.
If you have any question or just want to leave a message, just fill out the form below!
Your e-mail will not be visible in your post, it is for validation reasons only
Maffelu
Creator and admin of MorkaLork.com.
Started programming in HTML back when frames and tables was the way to design a page, moved on to Pascal/Delphi, PHP, javascript/jQuery, VB.NET/C#, Java and C++.
Currently studies .NET (in general) focusing on ASP.NET.
shruthi
2011-02-05 04:23:09
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 WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString =
"Host=Localhost;" +
"DataBase=shruthi;" +
"User id=root;" +
"Password=shruthi123;";
conn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
MySqlCommand cmd = new MySqlCommand("InsertMessage", new MySqlConnection());
cmd.CommandType