SQL connection example
A simple example that shows how to access a SQL database by using the System.Data.SqlClient library.
Author:
Jonas John
License:
Public domain
Language:
C#
Created:
08/09/2007
Updated:
08/09/2007
Tags:
database functions, sql, example
Related links:
// This example needs the // System.Data.SqlClient library #region Building the connection string string Server = "localhost"; string Username = "my_username"; string Password = "my_password"; string Database = "my_database"; string ConnectionString = "Data Source=" + Server + ";"; ConnectionString += "User ID=" + Username + ";"; ConnectionString += "Password=" + Password + ";"; ConnectionString += "Initial Catalog=" + Database; #endregion #region Try to establish a connection to the database SqlConnection SQLConnection = new SqlConnection(); try { SQLConnection.ConnectionString = ConnectionString; SQLConnection.Open(); // You can get the server version // SQLConnection.ServerVersion } catch (Exception Ex) { // Try to close the connection if (SQLConnection != null) SQLConnection.Dispose(); // Create a (useful) error message string ErrorMessage = "A error occurred while trying to connect to the server."; ErrorMessage += Environment.NewLine; ErrorMessage += Environment.NewLine; ErrorMessage += Ex.Message; // Show error message (this = the parent Form object) MessageBox.Show(this, ErrorMessage, "Connection error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Stop here return; } #endregion #region Execute a SQL query string SQLStatement = "SELECT * FROM ExampleTable"; // Create a SqlDataAdapter to get the results as DataTable SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(SQLStatement, SQLConnection); // Create a new DataTable DataTable dtResult = new DataTable(); // Fill the DataTable with the result of the SQL statement SQLDataAdapter.Fill(dtResult); // Loop through all entries foreach (DataRow drRow in dtResult.Rows) { // Show a message box with the content of // the "Name" column MessageBox.Show(drRow["Name"].ToString()); } // We don't need the data adapter any more SQLDataAdapter.Dispose(); #endregion #region Close the database link SQLConnection.Close(); SQLConnection.Dispose(); #endregion
Feel free to leave a message:
Add a comment
Helped a lot!!!!
Been looking for something that would show me how to use a datatable :-)
I was looking for a way to do multiple tables from SQL and reading them in the application :-)
Yay !!!
#region refresh button
private void button2_Click(object sender, EventArgs e)
{
textBox4.Clear();
string queryString = "SELECT database, Title, Publisher, Previewed, MovieYear, Type FROM movie,movieType WHERE movietype.typeID = movie.typeID";
loadDataGrid(queryString);
}
#endregion
#region Input
private void button6_Click(object sender, EventArgs e)
{
string typeString;
try
{
typeString = comboBox1.SelectedItem.ToString();
}
catch (Exception ex) {
MessageBox.Show("You must enter movie typenError: " + ex.Message + "");
return;
}
int type = 0;
string name = textBox1.Text.ToString();
string publisher = textBox2.Text.ToString();
string year = textBox3.Text.ToString();
int yr = 0;
if (year != "")
{
yr = CheckYear(year);
}
string previewed;
if (radioButton1.Checked == true)
{
previewed = "Yes";
}
else
{
previewed = "No";
}
if (yr != 1)
{
if (typeString == "Adventure") type = 1;
if (typeString == "Comedy") type = 2;
if (typeString == "Action") type = 3;
if (typeString == "Cartoon") type = 4;
if (typeString == "Romantic") type = 5;
if (typeString == "Fantasy") type = 6;
if (typeString == "Thriller") type = 7;
if (typeString == "Historic") type = 8;
if (typeString == "Drama") type = 9;
if (typeString == "Horor") type = 10;
if (typeString == "Sci-Fi") type = 11;
if (typeString == "Crime") type = 12;
if (typeString == "Biografy") type = 13;
if (typeString == "Documentary") type = 14;
string SQLString ="";
if (year == "")
{
SQLString = "INSERT INTO movie(Title, Publisher, Previewed, typeID) VALUES('" + name.Replace("'", "''") + "','" + publisher + "','" + previewed + "'," + type + ");";
}
else
{
MessageBox.Show(yr.ToString());
SQLString = "INSERT INTO movie(Title, Publisher, Previewed, MovieYear, typeID) VALUES('" + name.Replace("'", "''") + "','" + publisher + "','" + previewed + "'," + yr + "," + type + ");";
}
OleDbCommand SQLCommand = new OleDbCommand();
SQLCommand.CommandText = SQLString;
SQLCommand.Connection = database;
int response = -1;
try
{
response = SQLCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (response >= 1) MessageBox.Show("Movie is added to database","Successful",MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
comboBox1.ResetText();
radioButton1.Checked = radioButton2.Checked = false;
}
else
{
MessageBox.Show("The year format is not correct!nPlease try to pick a valid year.", "Warning",MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox3.Clear();
textBox3.Focus();
}
}
public int CheckYear(string year)
{
int yr = int.Parse(year);
if (yr >= 2100 || yr <= 1900)
{
return 1;
}
else
{
return yr;
}
}
#endregion
#region Delete/Edit button handling
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string queryString = "SELECT database, Title, Publisher, Previewed, MovieYear, Type FROM movie,movieType WHERE movietype.typeID = movie.typeID";
int currentRow = int.Parse(e.RowIndex.ToString());
try
{
string databaseString = dataGridView1[0, currentRow].Value.ToString();
databaseInt = int.Parse(databaseString);
}
catch (Exception ex) { }
// edit button
if (dataGridView1.Columns[e.ColumnIndex] == editButton && currentRow >= 0)
{
string title = dataGridView1[1, currentRow].Value.ToString();
string publisher = dataGridView1[2, currentRow].Value.ToString();
string previewed = dataGridView1[3, currentRow].Value.ToString();
string year = dataGridView1[4, currentRow].Value.ToString();
string type = dataGridView1[5, currentRow].Value.ToString();
//runs form 2 for editing
Form2 f2 = new Form2();
f2.title = title;
f2.publisher = publisher;
f2.previewed = previewed;
f2.year = year;
f2.type = type;
f2.database = databaseInt;
f2.Show();
dataGridView1.Update();
}
// delete button
else if (dataGridView1.Columns[e.ColumnIndex] == deleteButton && currentRow >= 0)
{
// delete sql query
string queryDeleteString = "DELETE FROM movie where database = "+databaseInt+"";
OleDbCommand sqlDelete = new OleDbCommand();
sqlDelete.CommandText = queryDeleteString;
sqlDelete.Connection = database;
sqlDelete.ExecuteNonQuery();
loadDataGrid(queryString);
}
}
Among this i ve introduced a refresh button in order to reactualizate the list from the table chosen to be shown in the datagridview.
to load the datagridview that i used to show the list from one able i used the following code:
public void loadDataGrid(string sqlQueryString) {
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView1.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView1.Columns.Clear(); // <-- clear columns
//---------------------------------
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView1.DataSource = data;
dataGridView1.AllowUserToAddRows = false; // remove the null line
dataGridView1.ReadOnly = true;
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[1].Width = 340;
dataGridView1.Columns[3].Width = 55;
dataGridView1.Columns[4].Width = 50;
dataGridView1.Columns[5].Width = 80;
// insert edit button into datagridview
editButton = new DataGridViewButtonColumn();
editButton.HeaderText = "Edit";
editButton.Text = "Edit";
editButton.UseColumnTextForButtonValue = true;
editButton.Width = 80;
dataGridView1.Columns.Add(editButton);
// insert delete button to datagridview
deleteButton = new DataGridViewButtonColumn();
deleteButton.HeaderText = "Delete";
deleteButton.Text = "Delete";
deleteButton.UseColumnTextForButtonValue = true;
deleteButton.Width = 80;
dataGridView1.Columns.Add(deleteButton);
}
P.S. :i used two buttons in the datagridview that appear in each row ,in order to delete or to edit the data directly from the interface into the database.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // <- for database methods
namespace Database
{
public partial class Form1 : Form
{
public OleDbConnection database;
DataGridViewButtonColumn editButton;
DataGridViewButtonColumn deleteButton;
int DatabaseInt;
#region Form1 constructor
public Form1()
{
InitializeComponent();
// initiate DB connection
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database.mdb";
try
{
database = new OleDbConnection(connectionString);
database.Open();
//SQL query to the list
string queryString = "here you must use the sql language in order to access you desired database";
loadDataGrid(queryString);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
#endregion
Thanks.
Convert.ToInt32(drRow["ID"].ToString());