C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: In Visual Studio, please click on Project, Add New Data Source. Select Database and click New Connection.
Tip: This is present on new installations of Visual Studio 2008 Professional. Newer versions also include this option.
Namespaces:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
Error:
Unhandled Exception: System.Data.SqlClient.SqlException:
There is already an object named... in the database.
Note: For more complex programs, you will prefer other techniques. Here is the method that creates the Dogs1 table.
TryCreateTable: We see the method will create the Dogs1 table with three columns. It stores the Weight, Name and Breed of the dog.
Info: Weight is stored as an int, while the other two fields are text fields (strings).
ExecuteNonQuery: This method is ideal for when you are inserting data, not reading it or querying for a specific result.
C# program that uses SqlCommand
/// <summary>
/// This method attempts to create the Dogs1 SQL table.
/// If will do nothing but print an error if the table already exists.
/// </summary>
static void TryCreateTable()
{
using (SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(
"CREATE TABLE Dogs1 (Weight INT, Name TEXT, Breed TEXT)", con))
{
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Table not created.");
}
}
}
Parameter: Every SqlCommand instance has a Parameter collection, which is an SqlParameterCollection and accessed with the Parameters property.
Add: We use the Add instance method to add new parameters. In the Add method, we call the new SqlParameter constructor.
SqlParameter: This constructor receives 2 arguments. First is the name of the variable in your command text, and second is the value object.
C# program that uses SqlParameter
/// <summary>
/// Insert dog data into the SQL database table.
/// </summary>
/// <param name="weight">The weight of the dog.</param>
/// <param name="name">The name of the dog.</param>
/// <param name="breed">The breed of the dog.</param>
static void AddDog(int weight, string name, string breed)
{
using (SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO Dogs1 VALUES(@Weight, @Name, @Breed)", con))
{
command.Parameters.Add(new SqlParameter("Weight", weight));
command.Parameters.Add(new SqlParameter("Name", name));
command.Parameters.Add(new SqlParameter("Breed", breed));
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Count not insert.");
}
}
}
Tip: Never insert data into a database table in raw form. Instead, please use SqlParameter and variable names, or question marks.
ToString: We see the ToString() method in this class. This is overrided and makes it easy for us to display the contents of the class Dog.
ToStringDefinition of Dog class: C#
/// <summary>
/// Encapsulates data for dog objects.
/// </summary>
public class Dog
{
public int Weight { get; set; }
public string Name { get; set; }
public string Breed { get; set; }
public override string ToString()
{
return string.Format("Weight: {0}, Name: {1}, Breed: {2}",
Weight, Name, Breed);
}
}
Here: In this example, we use the SqlConnection and SqlCommand ADO.NET patterns in the C# language.
Note: Look at the string parameter to the SqlCommand constructor, and it is an SQL command that selects all cells from each SQL table row.
Tip: The star in the command means "all". The "Dogs1" table from the database is also specified.
C# program that uses SqlDataReader
/// <summary>
/// Read in all rows from the Dogs1 table and store them in a List.
/// </summary>
static void DisplayDogs()
{
List<Dog> dogs = new List<Dog>();
using (SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0); // Weight int
string name = reader.GetString(1); // Name string
string breed = reader.GetString(2); // Breed string
dogs.Add(new Dog() { Weight = weight, Name = name, Breed = breed });
}
}
}
foreach (Dog dog in dogs)
{
Console.WriteLine(dog);
}
}
Finally: The foreach near the end of the example above displays the List collection that was filled with the data in the "Dogs1" table.
However: In other data-driven applications, you can use similar logic for inserting user data, such as that entered on web pages.
Here: Main first makes sure the database table we are using has been created. This is done by calling the custom TryCreateTable method.
ReadLine: The next few lines in the Main method above parse the Console input from the ReadLine method. It uses Split and int.Parse.
Splitint.ParseC# program that calls AddData
static void Main()
{
TryCreateTable();
while (true)
{
Console.WriteLine("INPUT TYPE:\tWeight,Name,Breed\tor\tSELECT:");
string[] input = Console.ReadLine().Split(',');
try
{
char c = char.ToLower(input[0][0]);
if (c == 's')
{
DisplayDogs();
continue;
}
int weight = int.Parse(input[0]); // The dog weight.
string name = input[1]; // The name string.
string breed = input[2]; // The breed string.
AddDog(weight, name, breed); // Add the data to the SQL database.
}
catch
{
Console.WriteLine("Input error");
}
}
}
Input
INPUT TYPE: Weight,Name,Breed or SELECT:
57,Koko,Shar Pei
INPUT TYPE: Weight,Name,Breed or SELECT:
130,Fido,Bullmastiff
INPUT TYPE: Weight,Name,Breed or SELECT:
93,Alex,Anatolian Shepherd Dog
INPUT TYPE: Weight,Name,Breed or SELECT:
25,Charles,Cavalier King Charles Spaniel
INPUT TYPE: Weight,Name,Breed or SELECT:
7,Candy,Yorkshire Terrier
INPUT TYPE: Weight,Name,Breed or SELECT:
s
Weight: 57, Name: Koko, Breed: Shar Pei
Weight: 130, Name: Fido, Breed: Bullmastiff
Weight: 93, Name: Alex, Breed: Anatolian Shepherd Dog
Weight: 25, Name: Charles, Breed: Cavalier King Charles Spaniel
Weight: 7, Name: Candy, Breed: Yorkshire Terrier
INPUT TYPE: Weight,Name,Breed or SELECT:
Output
Table not created.
INPUT TYPE: Weight,Name,Breed or SELECT:
s
Weight: 57, Name: Koko, Breed: Shar Pei
Weight: 130, Name: Fido, Breed: Bullmastiff
Weight: 93, Name: Alex, Breed: Anatolian Shepherd Dog
Weight: 25, Name: Charles, Breed: Cavalier King Charles Spaniel
Weight: 7, Name: Candy, Breed: Yorkshire Terrier
INPUT TYPE: Weight,Name,Breed or SELECT:
Complete program: C#
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
class Program
{
static void Main()
{
TryCreateTable();
while (true)
{
Console.WriteLine("INPUT TYPE:\tWeight,Name,Breed\tor\tSELECT:");
string[] input = Console.ReadLine().Split(',');
try
{
char c = char.ToLower(input[0][0]);
if (c == 's')
{
DisplayDogs();
continue;
}
int weight = int.Parse(input[0]);
string name = input[1];
string breed = input[2];
AddDog(weight, name, breed);
}
catch
{
Console.WriteLine("Input error");
}
}
}
/// <summary>
/// This method attempts to create the Dogs1 SQL table.
/// If will do nothing but print an error if the table already exists.
/// </summary>
static void TryCreateTable()
{
using (SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(
"CREATE TABLE Dogs1 (Weight INT, Name TEXT, Breed TEXT)", con))
{
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Table not created.");
}
}
}
/// <summary>
/// Insert dog data into the SQL database table.
/// </summary>
/// <param name="weight">The weight of the dog.</param>
/// <param name="name">The name of the dog.</param>
/// <param name="breed">The breed of the dog.</param>
static void AddDog(int weight, string name, string breed)
{
using (SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO Dogs1 VALUES(@Weight, @Name, @Breed)", con))
{
command.Parameters.Add(new SqlParameter("Weight", weight));
command.Parameters.Add(new SqlParameter("Name", name));
command.Parameters.Add(new SqlParameter("Breed", breed));
command.ExecuteNonQuery();
}
}
catch
{
Console.WriteLine("Count not insert.");
}
}
}
/// <summary>
/// Read in all rows from the Dogs1 table and store them in a List.
/// </summary>
static void DisplayDogs()
{
List<Dog> dogs = new List<Dog>();
using (SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0); // Weight int
string name = reader.GetString(1); // Name string
string breed = reader.GetString(2); // Breed string
dogs.Add(new Dog() { Weight = weight, Name = name, Breed = breed });
}
}
}
foreach (Dog dog in dogs)
{
Console.WriteLine(dog);
}
}
}
/// <summary>
/// Encapsulates data for dog objects.
/// </summary>
public class Dog
{
public int Weight { get; set; }
public string Name { get; set; }
public string Breed { get; set; }
public override string ToString()
{
return string.Format("Weight: {0}, Name: {1}, Breed: {2}",
Weight, Name, Breed);
}
}