I want to search data in database and put it in datatable but it seem my sql command its not correct because it didnt return any data. please help. thanks in advance. below is my code please check.
protected DataTable SearchResident(String name, String ConnStr)
{
DataTable dt = new DataTable();
try
{
SqlCommand cmd;
using (SqlConnection con = new SqlConnection(ConnStr))
{
con.Open();
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%name%' OR LastName LIKE '%name%'";
using (cmd = new SqlCommand(SQL, con))
{
using (SqlDataReader sdr = cmd.ExecuteReader())
{
dt.Load(sdr);
}
}
}
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
You wrote a request to the string SQL, but you do not use it in your code. Example SQL-query:
class SQLQuery
{
public static DataSet SQLGetData(string ConnectionString, string commandString)
{
DataSet DS = new DataSet();
DataTable DT = new DataTable("Table1");
DS.Tables.Add(DT);
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandString, connection);
//command.CommandTimeout = 3000;
SqlDataReader read = command.ExecuteReader();
DS.Load(read, LoadOption.PreserveChanges, DS.Tables[0]);
}
catch (SqlException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
finally
{
connection.Close();
}
}
return DS;
}
}
And get data:
private DataTable SearchData (string name)
{
DataTabel dt = new DataTable();
string connStr; // connection string
string command = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate,"+
"CivilStatus, Citizenship, MobileNo, Landline, PermanentAddress,"+
"Address FROM Residents WHERE FirstName LIKE '" + name +
"' OR LastName LIKE '" + name + "'";
dt = SQLQuery.SQLGetData(connStr, command).Tables[0];
return dt;
}
you need a sql command, and to add name as a parameter :-
using (SqlConnection con = new SqlConnection(ConnStr))
{
con.Open();
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%#name%' OR LastName LIKE '%#name%'";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#name", SqlDbType.Text);
cmd.Parameters["#name"].Value = name;
using (SqlDataReader sdr = cmd.ExecuteReader())
{
dt.Load(sdr);
}
}
You can use like this :
protected DataTable SearchResident(String name, String ConnStr)
{
try
{
String SQL = "SELECT ID, LastName, FirstName, MiddleName, Gender, BirthDate, CivilStatus, " +
"Citizenship, MobileNo, Landline, PermanentAddress, Address FROM Residents " +
"WHERE FirstName LIKE '%#name%' OR LastName LIKE '%#name%'";
using (SqlConnection sqlConn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(SQL, sqlConn))
{
cmd.Parameters.AddWithValue("#name", name);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
catch (Exception ex)
{
throw ex;
}
}
One more suggestion, you are inviting SQL injection. Please use a parameterized stored procedure.
Related
This is my SQL query and its running but I want to update a particular table column with this query so how and where I write update query?
public void Add()
{
SqlConnection sqlcon = new SqlConnection("server =(LocalDB)\\MSSQLLocalDB; Database = Online Medical Store ; integrated security = true");
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select LastName, FirstName, FatherName, Address, City, Contact, EmailAddress,BookSubject,BookTitle,EditionNumber,ISBN_Number,Issue_Date from IssueBooks where StudentID =#studentID and " +
"ISBN_Number = #isbnNumber", sqlcon);
cmd.Parameters.AddWithValue("#studentID", studentId);
cmd.Parameters.AddWithValue("#ISbnNumber", ISbnNumber);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
throw new Exception(" One Student Can Take Only One Book ");
}
else
{
SqlConnection con = new SqlConnection("server =(LocalDB)\\MSSQLLocalDB; Database = Online Medical Store ; integrated security = true");
con.Open();
SqlCommand sqlcmd = new SqlCommand("insert into IssueBooks(StudentID,LastName,FirstName,FatherName,Address, City," +
" Contact, EmailAddress, BookSubject, BookTitle,EditionNumber, ISBN_Number,Issue_Date)values" +
"(#studentID,#lastName,#firstName,#fatherName,#address,#city, #contact,#emailAddress,#BookSubject, #BookTitle, #EditionNumber, #ISBN_Number,#IssueDate)", con);
sqlcmd.Parameters.AddWithValue("#studentID", studentId);
sqlcmd.Parameters.AddWithValue("#lastName", LastName);
sqlcmd.Parameters.AddWithValue("#firstName", FirstName);
sqlcmd.Parameters.AddWithValue("#fatherName", FatherName);
sqlcmd.Parameters.AddWithValue("#address", Address);
sqlcmd.Parameters.AddWithValue("#city", City);
sqlcmd.Parameters.AddWithValue("#contact", Contact);
sqlcmd.Parameters.AddWithValue("#emailAddress", EmailAddress);
sqlcmd.Parameters.AddWithValue("#BookSubject", bookSubject);
sqlcmd.Parameters.AddWithValue("#BookTitle", bookTitle);
sqlcmd.Parameters.AddWithValue("#EditionNumber", EditionNumber);
sqlcmd.Parameters.AddWithValue("#ISBN_Number", isbnNumber);
sqlcmd.Parameters.AddWithValue("#IssueDate", Issue_Date);
sqlcmd.ExecuteNonQuery();
}
sqlcon.Close();
}
Code below is working properly and view all matches by search in column.
string sql = "SELECT car, model, year FROM store WHERE" + column + "LIKE " + search + "'";
Now adding parameters in query. Not working. It doesn't display search in column. Only display all rows in column, if search column of column ( 1 = 1)
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = "SELECT car, model, year FROM store WHERE #column like #search '";
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + searchCars.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + searchCars.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
What could possible be the answer to get it search within specific column?
Change it as follows so as to not parameterize the column name:
public int SearchCar(MainStore searchCars)
{
string connection = #"Data Source=(LocalDB)";
SqlConnection con = new SqlConnection(connection);
string sql = string.Format("SELECT car, model, year FROM store WHERE {0} like #search", search.GetCombo());
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
// sdt.SelectCommand.Parameters.AddWithValue("#column", "%" + search.GetCombo());
sdt.SelectCommand.Parameters.AddWithValue("#search", "%" + search.GetSearch());
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = data;
}
Also, you've got an extra quote at the end of your query:
like #search '";
Please take a look at this
private static void Select() {
string cmdStr = "SELECT FirstName, LastName, Telephone FROM Person WHERE FirstName = #FirstName";
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(cmdStr, connection)) {
command.Parameters.AddWithValue("#FirstName", "John");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string output = "First Name: {0} \t Last Name: {1} \t Phone: {2}";
Console.WriteLine(output, reader["FirstName"], reader["LastName"], reader["Telephone"]);
}
}
}
I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}
I would like to add into my query name of table from my string variable tablename. Is it possible in c#? I tried something like below. But it doesn't work. As you can see i want to set the FROM #tablename on scores
public void tableInsertTest()
{
MySqlConnection conn = null;
string tablename = "scores";
try
{
conn = new MySqlConnection(cs);
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 90;
cmd.CommandText = (
"INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
"SELECT NOW(), name, lname, score FROM #tablename " );
cmd.Prepare();
cmd.Parameters.AddWithValue("#tablename", tablename);
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return;
}
cmd.CommandText = ("INSERT INTO dailyrecords(recorddate, firstname, lastname, score ) " +
string.Format("SELECT NOW(), name, lname, score FROM {0} ", tablename) );
Your query is only a string and you have the value :)
I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:
SqlConnection con = new SqlConnection("Data Source = .;
Initial Catalog = domain;
Integrated Security = True");
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tablename", con);
I'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.
I tried this method but it's not working:
cmd.CommandText = "select * from tablename where firstname = '" + textBox1.Text + "' ";
How can I do it to retrieve all the other values to the textboxes?
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=#fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +"" part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=#fName"
oCmd.Parameters.AddWithValue("#fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person> .
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
create a class called DbManager:
Class DbManager
{
SqlConnection connection;
SqlCommand command;
public DbManager()
{
connection = new SqlConnection();
connection.ConnectionString = #"Data Source=. \SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True";
command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
} // constructor
public bool GetUsersData(ref string lastname, ref string firstname, ref string age)
{
bool returnvalue = false;
try
{
command.CommandText = "select * from TableName where firstname=#firstname and lastname=#lastname";
command.Parameters.Add("firstname",SqlDbType.VarChar).Value = firstname;
command.Parameters.Add("lastname",SqlDbType.VarChar).Value = lastname;
connection.Open();
SqlDataReader reader= command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
lastname = reader.GetString(1);
firstname = reader.GetString(2);
age = reader.GetString(3);
}
}
returnvalue = true;
}
catch
{ }
finally
{
connection.Close();
}
return returnvalue;
}
then double click the retrieve button(e.g btnretrieve) on your form and insert the following code:
private void btnretrieve_Click(object sender, EventArgs e)
{
try
{
string lastname = null;
string firstname = null;
string age = null;
DbManager db = new DbManager();
bool status = db.GetUsersData(ref surname, ref firstname, ref age);
if (status)
{
txtlastname.Text = surname;
txtfirstname.Text = firstname;
txtAge.Text = age;
}
}
catch
{
}
}
To retrieve data from database:
private SqlConnection Conn;
private void CreateConnection()
{
string ConnStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
Conn = new SqlConnection(ConnStr);
}
public DataTable getData()
{
CreateConnection();
string SqlString = "SELECT * FROM TableName WHERE SomeID = #SomeID;";
SqlDataAdapter sda = new SqlDataAdapter(SqlString, Conn);
DataTable dt = new DataTable();
try
{
Conn.Open();
sda.Fill(dt);
}
catch (SqlException se)
{
throw;
}
catch (Exception ex)
{
throw;
}
finally
{
Conn.Close();
}
return dt;
}
You can use this simple method after setting up your connection:
private void getAgentInfo(string key)//"key" is your search paramter inside database
{
con.Open();
string sqlquery = "SELECT * FROM TableName WHERE firstname = #fName";
SqlCommand command = new SqlCommand(sqlquery, con);
SqlDataReader sReader;
command.Parameters.Clear();
command.Parameters.AddWithValue("#fName", key);
sReader = command.ExecuteReader();
while (sReader.Read())
{
textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
//["LastName"] the name of your column you want to retrieve from DB
textBoxAge.Text = sReader["age"].ToString();
//["age"] another column you want to retrieve
}
con.Close();
}
Now you can pass the key to this method by your textBoxFirstName like:
getAgentInfo(textBoxFirstName.Text);
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case
"DbConnectionString")
DataTable formerSlidesData = new DataTable();
DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
if (formerSlidesData.Rows.Count > 0)
{
DataRow rowa = formerSlidesData.Rows[0];
cabinet = Convert.ToInt32(rowa["cabinet"]);
box = Convert.ToInt32(rowa["box"]);
drawer = Convert.ToInt32(rowa["drawer"]);
}