Embedding generic sql queries into c# program - c#

Okay referring to my first question code in the main, I want the user to enter employee name at runtime and then i take this name which user has entered and compare it with the e_name of my emp table , if it exists i want to display all information of that employee , how can I achieve this ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ConnectCsharppToMySQL
{
public class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
string name;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "test";
uid = "root";
password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//Insert statement
public void Insert()
{
string query = "INSERT INTO emp (e_name, age) VALUES('Pooja R', '21')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Update statement
public void Update()
{
string query = "UPDATE emp SET e_name='Peachy', age='22' WHERE e_name='Pooja R'";
//Open connection
if (this.OpenConnection() == true)
{
//create mysql command
MySqlCommand cmd = new MySqlCommand();
//Assign the query using CommandText
cmd.CommandText = query;
//Assign the connection using Connection
cmd.Connection = connection;
//Execute query
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
//Select statement
public List<string>[] Select()
{
string query = "SELECT * FROM emp where e_name=(/*I WANT USER ENTERED NAME TO GET INSERTED HERE*/)";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["e_id"] + "");
list[1].Add(dataReader["e_name"] + "");
list[2].Add(dataReader["age"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
public static void Main(String[] args)
{
DBConnect db1 = new DBConnect();
Console.WriteLine("Initializing");
db1.Initialize();
Console.WriteLine("Search :");
Console.WriteLine("Enter the employee name");
db1.name = Console.ReadLine();
db1.Select();
Console.ReadLine();
}
}
}

This method will need to accept a parameter:
public List<string>[] Select()
Something like this, most likely:
public List<string>[] Select(string name)
Then, within that method, you can reference the name variable. When calling that method, you would supply that variable:
var listOfResults = dbConnectInstance.Select(someNameValue);
Once that variable is in your method, you can use it in your SQL query. You would do this by setting it as a parameter in your SELECT query. Something like this, perhaps (keep in mind this is free-hand code, I don't have the MySql .NET library handy to test):
string query = "SELECT * FROM emp where e_name=#ename";
//... (opening the connection like you do now, etc.)
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.Add("#ename", MySqlDbType.VarChar, 80).Value = name;
//... (continuing as you do now)
What this essentially does is create a placeholder in the query called #ename (it can be called anything, the # is the important part for being a placeholder) which expects to be replaced with an actual value. Adding an item to the Parameters collection on the command object is what replaces the placeholder with the value.
This is called "parameterized queries" in ADO.NET (which is the database connection technology you're using). It helps keep your queries dynamic (one query can be re-used with different values) as well as helps prevent SQL injection attacks (note that I said helps prevent, as it's not a magic bullet and increased understanding of the subject in general is your best defense).
More information specifically about the MySql .NET library's queries and parameters can be found starting here.

use MySqlParameter as :
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand ("SELECT * FROM emp where e_name =#Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.AddWithValue("#Name", name);// name is get from console read line.
//
// Read in the SELECT results.
//
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// read each value
}
}
}
EDIT
here are the changes you need to do
//add name as Select method parameter
public List<string>[] Select(string name)
{
string query = "SELECT * FROM emp where e_name =#Name"; // change your select query
....
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.Parameters.AddWithValue("#Name", name) // add this line after creating command
....
}
call above method as
db1.name = Console.ReadLine();
db1.Select(db1.name);

Related

How do i add my customer data into a SQL database?

This is my CustomerRegister class, but I cant seem to input data from my addressTextBox into the CustomerTbl.
DataBase dbObj = new DataBase();
string selStr = "Update CustomerTbl Set customer_address = '" + addressTextBox.Text + "' Where custID = " + "NULL";
int i = dbObj.ExecuteNonQuery(selStr);
This is my DataBase class but return comdObj.ExecuteNonQuery(); doesnt work as there is not such custID named NULL. So how do i program in such a way so that i am able to constantly update the database when a new user registers?
class DataBase
{
string connStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\OOPG\Banking Mini Project Raynard\Banking Mini Project Raynard\Database1.mdf;Integrated Security = True";
SqlConnection connObj;
SqlCommand comdObj;
SqlDataReader dR;
public DataBase()
{
connObj = new SqlConnection(connStr);
connObj.Open();
}
public SqlDataReader ExecuteReader(string selStr)
{
comdObj = new SqlCommand(selStr, connObj);
dR = comdObj.ExecuteReader();
return dR;
}
public int ExecuteNonQuery(string sqlStr)
{
comdObj = new SqlCommand(sqlStr, connObj);
return comdObj.ExecuteNonQuery();
}
}
First you should create a connection to SQL database before executing any query. After then you should be able to insert data before updating any data into database. After you insert data successfully you can update data using above command text. Here is some sample code for inserting data for registering customer.
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT into CustomerTbl (CustId, Name, Address) VALUES (#CustId, #Name, #Address)";
command.Parameters.AddWithValue("#CustId", name);
command.Parameters.AddWithValue("#Name", userId);
command.Parameters.AddWithValue("#Address", idDepart);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
If you're adding a record, you're going to need to INSERT, not UPDATE. For example (here using "Dapper" to do all the heavy work, including parameter handling):
using Dapper;
//...
void UpsertAddress(int? id, string address)
{
if (id is null)
{
connection.Execute("insert CustomerTbl (customer_address) values (#address);",
new { address }); // possibly using the OUTPUT clause to fetch an IDENTITY
}
else
{
connection.Execute(
"update CustomerTbl set customer_address = #address where custID = #id;",
new { id, address });
}
}

Unable to Get value from MySQL and print to TextBox

So this method is supposed to get the ipaddress of the logged in user from a MySQL Database and print it to a textbox. However, I cant seem to get it right as the program just closes after I execute this method.
public void readIPAddress()
{
string username = GlobalData._sharedUserName;
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "SELECT ipaddress FROM webappdemo.userregistration WHERE username=?username";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("?username", username);
cmd.ExecuteReader();
while (cmd.ExecuteReader().Read())
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
conn.Close();
}
If anyone could point out where I went wrong, I greatly appreciate your help!
Edit: After using try and catch I get this:
MySql.Data.MySqlClient.MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first.
at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
at MySql.Data.MySqlClient.MySqlCommand.CheckState()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at ConnectToDataBase.Form2.readIPAddress() in C:\Users\ee\Dropbox\ConnectToDataBase\ConnectToDataBase\Form2.cs:line 95
Quick Fix:
You are executing the command two times, using ExecuteReader that's why you are getting such exception. If you execute the code like this means your code will works fine:
string queryStr = "SELECT ipaddress FROM webappdemo.userregistration WHERE username=#username";
using (MySqlConnection conn = new MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(queryStr, conn))
{
cmd.Parameters.AddWithValue("#username", username);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
}
}
Smart Fix:
Here you are fetching a single value from the database in such situations you need not to use reader at all. you can simply access those value by using ExecuteScalar() method, which will give you the required object. if so You can use the following code:
using(MySqlConnection conn = new MySqlConnection(connString))
{
using(MySqlCommand cmd= new MySqlCommand(query, conn))
{
cmd.Parameters.Add("#username", username);
conn.Open();
object ipAddress= cmd.ExecuteScalar();
if (ipAddress!= null)
textBoxIPAddress.Text = ipAddress.ToString();
else
textBoxIPAddress.Text = "No data found";
}
}
Hope that you wont forget to add MySql.Data.MySqlClient; to the using section
you are executing reader two times by calling ExecuteReader(), why you need Reader here, if you only need one value from database. use ExecuteScalar that will return first value of the first record from the result. Sample code:
try
{
string query = "SELECT ipaddress FROM webappdemo.userregistration WHERE username = #username";
string connString =ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
using(MySqlConnection connection = new MySqlConnection(connString))
{
using(MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.Add("#username", username);
connection.Open();
object ip= command.ExecuteScalar();
if (ip != null) {
textBoxIPAddress.Text = ip.ToString();
}
}
}
}
catch(MySqlException ex)
{
// do something with the exception
}
Problem:
cmd.ExecuteReader(); //Executing reader and not assigning to anything
while (cmd.ExecuteReader().Read()) //Executing reader again and not assigning to anything again
{
//There is nothing assigned to reader.
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
Quick Solution:
//assuming reader is defined
reader = cmd.ExecuteReader();
while (reader.Read()) //read from the reader
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
Alternative Solutions using MySql.Data.MySqlClient.MySqlHelper:
try {
object ip = MySqlHelper.ExecuteScalar(connString, query, new MySqlParameter[] {
new MySqlParameter("?username", username)
}));
if (ip != null) {
textBoxIPAddress.Text = ip.ToString();
}
} catch (Exception ex) {
// do something with the exceptio
}
If you insist on using reader:
//assuming reader is defined
reader = MySqlHelper.ExecuteReader(connString, query, new MySqlParameter[] {
new MySqlParameter("?username", username)
}));
while (reader.Read()) //read from the reader
{
textBoxIPAddress.Text = reader["ipaddress"].ToString();
}
Note: the above code is just typed in here and may contain syntax errors. take this a a guideline.

How to Query Return Value on using Compact SQL Command?

I using a compact database created on visual studio. just for a stand alone system with it's database intact already although i'm stuck here in using a select query that could retrieve a boolean if the user exist on the database and also then return it's ID and Username if the user entry exist. can i ask for help regarding on this one.. I am a student trying to learn c# on using compact database.
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (!IsEmpty())
{
if (!IsLenght())
{
using (SqlCeConnection con = new SqlCeConnection("Data Source=" +
System.IO.Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = (bool)cmd.ExecuteScalar();
con.Close();
MessageBox.Show(validlogin.ToString());
if (validlogin == true)
{
// cmd. return value ID
// cmd. return value Username
//SysMain Mn = new SysMain();
//Mn.ShowDialog();
//this.Hide();
}
}
}
}
}
catch (Exception ex)
{
gbf.msgBox(1, ex.Message.ToString(), "");
}
}
The code below is probably better, unless there is something special and unstated about the schema of LoginTB.
// ...
var validLogin = false;
using (SqlCeConnection con = new SqlCeConnection(
"Data Source=" +
System.IO.Path.Combine(
Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location),
"INCdb.sdf")))
{
con.Open();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText =
"SELECT COUNT(*) FROM LoginTB Where username=#user1 AND password=#pass1";
cmd.Parameters.AddWithValue("#user1", UserTxt.Text.Trim());
cmd.Parameters.AddWithValue("#pass1", PassTxt.Text.Trim());
cmd.CommandType = CommandType.Text;
validlogin = ((int)cmd.ExecuteScalar()) > 0;
}
MessageBox.Show(validlogin.ToString());
// ...
Note the use of COUNT

ConnectionString not initiated after inserting!

I'm having this little issue : each time my code executes the InsertOrder() routine below, i get this exception message : "connection string has not been initiated".
Here's the code of InsertOrder() method:
private void InsertOrder()
{
string insertSQL = "";
insertSQL += "INSERT INTO Orders (";
insertSQL += "UserName, DateCreated, LastUpdate, Description, PaymentType, Delivery, Total) ";
insertSQL += "VALUES (#UserName, #DateCreated, #LastUpdate, #Description, #PaymentType, #Delivery, #Total)";
SqlCommand cmd0 = new SqlCommand(insertSQL, connection);
// Adds the parameters
cmd0.Parameters.AddWithValue("#UserName", Profile.UserName.ToString());
cmd0.Parameters.AddWithValue("#DateCreated", Profile.Orders.SCart.DateCreated());
cmd0.Parameters.AddWithValue("#LastUpdate", Profile.Orders.SCart.LastUpdate());
cmd0.Parameters.AddWithValue("#Description", Profile.Orders.SCart.GetCartDescription());
cmd0.Parameters.Add("#PaymentType", SqlDbType.Bit).Value = Profile.Orders.SCart.PaymentType;
cmd0.Parameters.Add("#Delivery", SqlDbType.Bit).Value = Profile.Orders.SCart.Delivery;
cmd0.Parameters.AddWithValue("#Total", Profile.Orders.SCart.Total);
try
{
using (connection)
{
connection.Open();
cmd0.ExecuteNonQuery();
}
string selectSQL = "SELECT OrderID FROM Orders WHERE UserName=#UserName AND DateCreated=#DateCreated";
SqlCommand cmd1 = new SqlCommand(selectSQL, connection);
cmd1.Parameters.AddWithValue("#UserName", Profile.UserName);
cmd1.Parameters.AddWithValue("#DateCreated", Profile.Orders.SCart.DateCreated());
SqlDataReader reader;
using (connection)
{
connection.Open();
reader = cmd1.ExecuteReader();
reader.Read();
OrderID = (int)reader["OrderID"];
reader.Close();
}
// Store registered customer information for later usage..
if (!Profile.IsAnonymous)
{
string insertSQL2 = "";
insertSQL2 += "INSERT INTO CategoriesInAnOrder (";
insertSQL2 += "OrderID, CategoryID, Quantity) VALUES (#OrderID, #CategoryID, #Quantity)";
foreach (CartItem item in Profile.Orders.SCart.Items)
{
SqlCommand cmd2 = new SqlCommand(insertSQL2, connection);
cmd2.Parameters.AddWithValue("#OrderID", OrderID);
cmd2.Parameters.AddWithValue("#CategoryID", item.CategoryID);
cmd2.Parameters.AddWithValue("#Quantity", item.Quantity);
using (connection)
{
connection.Open();
cmd2.ExecuteNonQuery();
}
}
}
}
catch (Exception err)
{
pnlWizard.Visible = false;
lblError.Text = err.Message;
}
}
Probabily it's worth saying i have placed a SqlConnection object inside my SuperClass, so every child class (like the one which contains the above method) inherits this attribute.
The shared SqlConnection object is set as follows:
protected SqlConnection connection = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString);
Sorry for my english... i'm italian
I think the
using(connection)
may be the source of your problem.
The using() is going to cause Dispose() to be called on the connection when the call has completed, but your connection is only being instantiated once.
Next time you come to use it, it's not going to be in a healthy state!
Consider creating a new connection each time:
protected SqlConnection connection
{
get
{
return new SqlConnection
(System.Web.Configuration.WebConfigurationManager.ConnectionStrings
["DefaultConnectionString"].ConnectionString);
}
}
I suspect the problem is that you are using the value from a field. That will work once, but after the Dispose() you have doomed that connection.
For this scenario, I use a custom EnsureOpen() method that returns an IDisposable if it wasn't already open; usage:
using(connection.EnsureOpen())
{
// use it
}
This way the connection isn't disposed prematurely but is open when needed. Plus it works whether it was already open or not.
I can share EnsureOpen later if you want.

C# MySql Storing multiple database rows in C#

I'm struggling a bit with this. I want to get the list of ids from the database where a certain value is equal to a certain value in the row. This call will likely return multiple ids. I want to store the value in the ids returned in a list or arraylist in the c# code but I am finding this troublesome. I have the code up to here:
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers + "";
connection.Open();
reader = command.ExecuteReader();
Any help would be much appreciated
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
List<string> array = new List<string>();
using (MySqlCommand cmd = new MySqlCommand("SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers, connection))
{
try
{
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
array.Add(Reader["idprojects"].ToString());
}
}
}
catch (Exception ex)
{
throw;
}
}
string[] ret= array.ToArray();

Categories

Resources