Inserting into database from C# console application
Creating the table and inserting into database by using Console application of C#.net.
Here I have used, System.Data.SqlClient name space.
First I have created a table in data base and inserted into the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
SqlConnection MyConn = new SqlConnection("server=(local)S;database=MyDB;Integrated Security=SSPI");
SqlCommand command = MyConn.CreateCommand();
try
{
MyConn.Open();
command.CommandText = "CREATE DATABASE MyDb";
Console.WriteLine(command.CommandText);
command.ExecuteNonQuery();
Console.WriteLine("Database created, now switching");
MyConn.ChangeDatabase("MyDb");
command.CommandText = "CREATE TABLE tbl1 (COL1 integer)";
Console.WriteLine(command.CommandText);
Console.WriteLine("Number of Rows Affected is: {0}", command.ExecuteNonQuery());
command.CommandText = "INSERT INTO tbl2 VALUES (99)";
Console.WriteLine(command.CommandText);
Console.WriteLine("Number of Rows Affected is: {0}", command.ExecuteNonQuery());
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
MyConn.Close();
Console.WriteLine("Data base Connection Closed.");
}
}
}
}
Regards,
Naveen