I need to query my database for found person by keyin name " space " surname, name and surname are both in different column in the same table.
When user key in in textbox, query must be some thing like:
string valueToSearch = MyTextBox.Text.ToString();
searchUserData(valueToSearch);
public void searchUserData(string valueToSearch)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = MyConstring;
string searchQuery = "SELECT [NDM],[Prenom],[Nom],[Sex],[DateNaiss],[Adresse],[Tel] FROM [Lab062016].[dbo].[LabPatients] WHERE Nom LIKE '%" + valueToSearch + "%' OR Prenom LIKE '%" + valueToSearch + "%' ";
SqlCommand cmande = new SqlCommand(searchQuery.ToString(), conn);
SqlDataAdapter adapter;
DataTable table;
adapter = new SqlDataAdapter(cmande);
table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
Related
public void filter()
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
SqlDataAdapter sqlad = new SqlDataAdapter("select * From Customer", sqlconn);
DataTable dtbl = new DataTable();
sqlad.Fill(dtbl);
DataView dv = dtbl.DefaultView;
dv.RowFilter = string.Format("Name like '%{0}%' and Address like '%{0}% and office_number like '" + searchoffice.Text + "%'and phone_number like '" + searchphone.Text + "%' and acount_name like '%{0}%'", searchname.Text,searchaddress.Text,searchoffice.Text,searchphone.Text,searchaccountname.Text);
customergrid.DataSource = dv.ToTable();
dtbl.DefaultView.Sort = "[Name] DESC";
}
}
When I run this method in the textbox.textchange()-EventHandler, I get following Exception:
The expression contains an invalid string constant: '
Please help me fix the exception.
It seems that your query string was missing one space near office_number like '" + searchoffice.Text + "%' and phone_number, also there was one '-character missing and String.Format- parameter count mismatch.
So try following:
public void filter()
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
SqlDataAdapter sqlad = new SqlDataAdapter("select * From Customer", sqlconn);
DataTable dtbl = new DataTable();
sqlad.Fill(dtbl);
DataView dv = dtbl.DefaultView;
dv.RowFilter = string.Format("Name like '%{0}%' and Address like ‘%{1}%’ and office_number like '" + searchoffice.Text + "%' and phone_number like '" + searchphone.Text + "%' and acount_name like '%{0}%'", searchname.Text,searchaddress.Text);
customergrid.DataSource = dv.ToTable();
dtbl.DefaultView.Sort = "[Name] DESC";
}
}
How can I also search my id, middlename, lastname in my search text box? I cant use WHERE CONCAT() because my database is just a built-in in microsoft visual studio 2010
private void textBox14_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox14.Text))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * from table1", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
else
{
SqlDataAdapter sda = new SqlDataAdapter("SELECT id, FirstName, MiddleName, LastName, Gender, DateofBirth, PlaceofBirth, Address, FathersName, FathersOccupation, MothersName, MothersOccupation, Guardian, Relation, GuardianOccupation, image FROM table1 WHERE FirstName LIKE'" + textBox14.Text + "%'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
}
You can use OR to the multiple things you want to search from the textbox. Try this:
private void textBox14_TextChanged(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox14.Text))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * from table1", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
else
{
SqlDataAdapter sda = new SqlDataAdapter("SELECT id, FirstName, MiddleName, LastName, Gender, DateofBirth, PlaceofBirth, Address, FathersName, FathersOccupation, MothersName, MothersOccupation, Guardian, Relation, GuardianOccupation, image FROM table1 WHERE FirstName LIKE'" + textBox14.Text + "%' OR id LIKE'" + textBox14.Text + "%' OR MiddleName LIKE'" + textBox14.Text + "%' OR LastName LIKE'" + textBox14.Text + "%'", con);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
}
}
I am trying to get search query
Its in asp.net c# please help me for search query.
protected void btnreg_Click(object sender, EventArgs e)
{
string search = query.Text;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE search LIKE '%' + nor + '%' OR recipe LIKE '%' + search + '%' OR ingredients LIKE '%' + search + '%' OR type_of_food LIKE '%' + search + '%' OR type_of_meal LIKE '%' + search + '%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}}
I suppose 'nor' is a column name in your table .. try the following :-
protected void btnreg_Click(object sender, EventArgs e)
{
string search = query.Text;
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '%'" + search + "'%' OR recipe LIKE '%' "+ search + "'%' OR ingredients LIKE '%' "+ search + "'%' OR type_of_food LIKE '%' "+ search + "'%' OR type_of_meal LIKE '%' "+ search +" '%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}
}
Actually you cannot enclose the varibale search inside the "double quotes" tag .
Hope this helps you .
Cheers !
Why not use Parameterized Queries !
E.g
var command = "SELECT * FROM recipe WHERE recipe LIKE '% #Receipe %'";
var cmd= new SqlCommand(command , yourconnetion);
cmd.Parameters["#Receipe "].Value =query.Text;
OR
cmd.Parameters.AddWithValue("#Receipe ",query.Text);
Read more about How and Why to Use Parameterized Queries
Finally I got the right one, it goes like this.
Although thanks for help guys.
protected void btnreg_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '%" + query.Text + "%' OR recipe LIKE '%" + query.Text + "%' OR ingredients LIKE '%" + query.Text + "%' OR type_of_food LIKE '%" + query.Text + "%' OR type_of_meal LIKE '%" + query.Text + "%' ", con);
DataTable dt = new DataTable();
da.Fill(dt);
repeter.DataSource = dt;
repeter.DataBind();
}
Use `Parametarized` and `Using{}` statement to auto dispose and close connection
using( SqlConnection objConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
objConnection.Open();
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM recipe WHERE nor LIKE '% #query %'" , con))
DataTable dt= new DataTable();
da.SelectCommand.Parameters.AddWithValue("#query",query.Text);
da.Fill(dt);
}
catch(System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
I am very new to sqlite and c# and trying exporting a csv file to sqlite database using dataset.
but I get this error.
SQL logic error or missing database
no such column: P17JAW
code:
string strFileName = "I:/exploretest.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];
SQLiteConnection m_dbConnection;
m_dbConnection = new SQLiteConnection("Data Source= C:/Users/WebMobility.db; Version=3;");
m_dbConnection.Open();
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var Id = dr["Id"].ToString();
var VRM = dr["VehicleRegistration"].ToString();
var Points = Convert.ToInt32(dr["TicketScore"].ToString());
string sql = "insert into NaughtyList (Id,VRM,Points) values ( '" + Id + "'," + VRM + "," + Points + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
CSV FILE CONTAINS
Id,VehicleRegistration,TicketScore
21,P17JAW,1
22,K1WOM,1
23,m4npr,4
25,G7EPS,4
Your problem is with the single quotes missing for VRM your query should be like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
( '" + Id + "','" + VRM + "'," + Points + ")";
//^^ ^^
From the values it appears that ID is of integer type, you can remove single quotes around ID.
You should parameterized your query that will save your from these errors. I am not sure if parameters are supported by SQLiteCommand if they are you can do something like:
string sql = #"insert into NaughtyList (Id,VRM,Points) values
(#Id,#VRM,#Points)";
and then
command.Parameters.AddWithValue("#id", Id);
command.Parameters.AddWithValue("#VRM", VRM);
command.Parameters.AddWithValue("#Points", Points);
I have this code here:
public class clsDataLayer
{
// This function saves the personnel data
public static bool SavePersonnel(string Database, string FirstName, string LastName,
string PayRate, string StartDate, string EndDate)
{
bool recordSaved;
try
{
// Retrieving information
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Inserting information into the table
strSQL = "Insert into tblPersonnel " +
"(FirstName, LastName, PayRate, StartDate, EndDate) values ('" +
FirstName + "', '" + LastName + "', " + PayRate + ", '" + StartDate +
"', '" + EndDate + "')";
// Gets the statement to execute at the data source
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Executes the SQL statement and returns the number of rows
command.ExecuteNonQuery();
// Closes the connection to the data source
conn.Close();
recordSaved = true;
}
catch (Exception)
{
recordSaved = false;
}
return recordSaved;
}
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// States the classes used
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Defines sqlConnclass and what each will consist of
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Defines sqlDA and what each will consist of
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Defines DS and what each will consist of
DS = new dsUserActivity();
// Outputs the results from the information gathered
sqlDA.Fill(DS.tblUserActivity);
// Starts over for a new user
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Defines the connection to the database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
public clsDataLayer()
{
}
public static dsPersonnel GetPersonnel(string p)
{
throw new NotImplementedException();
}
}
I need to add this code but everytime I do I get an error that says No overload for method 'GetPersonnel' takes '1' arguments
// This function gets the user activity from the tblPersonnel
public static dsPersonnel GetPersonnel(string Database, string strSearch)
{
dsPersonnel DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
//create the connection string
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
string query;
if (strSearch == "" || strSearch.Trim().Length == 0)
{
query = "SELECT * from tblPersonnel";
}
else
{
query = "select * from tblPersonnel where LastName = '" + strSearch + "'";
}
// Defines sqlDA and what each will consist of
sqlDA = new OleDbDataAdapter("select * from tblPersonnel", sqlConn);
// Defines DS and what each will consist of
DS = new dsPersonnel();
// Outputs the results from the information gathered
sqlDA.Fill(DS.tblPersonnel);
// Starts over for a new user
return DS;
}
// This function saves the user activity
public static void SavePersonnel(string Database, string FormAccessed)
{
// Defines the connection to the database
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblPersonnel (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
It looks like you're defining
public static dsPersonnel GetPersonnel
twice in the same class. I suspect you are REPLACING the single-arg version with the two-arg version but somewhere you're still calling the single-arg version.
I know you're not asking for this sort of input, but I can't help myself...
You should wrap your OleDbConnections in a using block to make sure they get closed like so:
using (OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database))
{
conn.Open();
...
{
Not sure where your strSearch data is coming from, but you're setting yourself up for a nasty SQL Injection attack with this line:
query = "select * from tblPersonnel where LastName = '" + strSearch + "'";
you should use SQL parameters or a stored procedure.