Query works in Access but not in my program. Why? - c#

I have this query set up in my application to work for searching through my database. I put this query into Access and it works fine. However, when I put it into my program the table has 0 entries. Can you please help?
private async Task FilterDB()
{
List<string> Filter = new List<string>();
if (CardNameCheck.IsChecked == true)
Filter.Add("*" + CardNameBox.Text + "*");
else
Filter.Add("*");
if (CardExpanCheck.IsChecked == true)
Filter.Add("*" + CardExpanBox.Text + "*");
else
Filter.Add("*");
OleDbConnection DBCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Properties.Settings.Default.DatabaseLocation);
await DBCon.OpenAsync();
OleDbDataAdapter CardDA = new OleDbDataAdapter("SELECT * FROM Cards WHERE Name like '" + Filter[0] + "' and Expansion like '" + Filter[1] + "'", DBCon);
DataSet CardDS = new DataSet();
CardDA.Fill(CardDS);
DBCon.Close();

I tried your code and modified it a bit. Works for me for the Access2003 .mdb format.
OleDbConnection DBCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=(k:\mydatabases\mydatabase.mdb");
DBCon.Open();
// Create a select Command - you need System.Data.OleDb and System.Data for this
OleDbCommand selectCommand = new OleDbCommand();
// define the CommandText with two parameters #Filter1 and #Filter2
selectCommand.CommandText = "SELECT * FROM Cards WHERE Name like #Filter1 and Expansion like #Filter2";
selectCommand.Connection = DBCon;
// Create two string / VarChar Parameters -
// the following is a standard I commonly use
// for string/varchar; you might also use OleDbType.NVarChar
OleDbParameter param01 = new OleDbParameter();
param01.ParameterName = "Filter1";
param01.DbType = DbType.AnsiString;
param01.OleDbType = OleDbType.VarChar;
param01.SourceVersion = DataRowVersion.Current;
param01.SourceColumn = "Name";
// provide them with values - I used text boxes for input
// use '%' for like statement - if no parameter provided use single '%' only
if (txtFilter1.Text.ToString().Equals(""))
{
param01.Value = '%';
}
else
{
param01.Value = '%' + txtFilter1.Text.ToString() + '%';
}
// add the parameter to the SelectCommand
selectCommand.Parameters.Add(param01);
// same goes for the second parameter
OleDbParameter param02 = new OleDbParameter();
param02.ParameterName = "Filter2";
param02.DbType = DbType.AnsiString;
param02.OleDbType = OleDbType.VarChar;
param02.SourceVersion = DataRowVersion.Current;
param02.SourceColumn = "Expansion";
if (txtFilter2.Text.ToString().Equals(""))
{
param02.Value = '%';
}
else
{
param02.Value = '%' + txtFilter2.Text.ToString() + '%';
}
selectCommand.Parameters.Add(param02);
OleDbDataAdapter CardDA = new OleDbDataAdapter();
// tell the DataAdapter to use a SelectCommand
CardDA.SelectCommand = selectCommand;
CardDA.GetFillParameters(); // actually not sure if you need this but does no harm either
DataSet CardDS = new DataSet();
CardDA.Fill(CardDS, "TargetTable");
DBCon.Close();
foreach(DataRow row in CardDS.Tables["TargetTable"].Rows)
{
// do something ;
}
Good luck!

Related

Number of query values and destinations fields are not the same

This is the function for automatically stored value to TotalAmt_tx.Text..
void TotalAmount()
{
.
.
.
.
TotalAmt_tx.Text = Total.ToString("00.00");
.
.
.
catch { }
}
Save button code :here the image of my forms
private void Save_bt_Click(object sender, EventArgs e)
{
//Purchase Table
{
string insertPur = "Insert into Purchase (Invoice,VendorName,PurchaseDate,TotalAmt) values ("+Invoice_tx.Text+"," +
"'"+VendorName_cb.Text+"','"+PurchaseDate_dt.Value.Date.ToString()+"',"+TotalAmt_tx.Text+" )";
OleDbDataAdapter da = new OleDbDataAdapter(insertPur, conn);
DataSet ds = new DataSet();
da.Fill(ds);
}
//Purchase Item Table
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
string insertPur = "Insert into PurchaseItem (Invoice, PId, Product, Qty, Rate, Amount) values (" + Invoice_tx.Text + "," +
""+metroGrid1.Rows[i].Cells["PId"].Value.ToString()+ ",'" + metroGrid1.Rows[i].Cells["Product"].Value.ToString() + "'," +
"" + metroGrid1.Rows[i].Cells["Qty"].Value.ToString() + "," + metroGrid1.Rows[i].Cells["Rate"].Value.ToString() + "," +
"" + metroGrid1.Rows[i].Cells["Amount"].Value.ToString() + ")";
OleDbDataAdapter da = new OleDbDataAdapter(insertPur, conn);
DataSet ds = new DataSet();
da.Fill(ds);
}
MessageBox.Show("Data Saved!!");
The problems show up because this
TotalAmt_tx.Text = Total.ToString("00.00")
What should I do, to solve it??
I've try follow some tutorial about formatting string but nothings works.
Please help
I suggest you try to use OleDbParameter Class, because if one of the values you combine to your query string has the , character it will mess-up you query (for example a number in the following format 1,000).
Hope it helps!
You should always stick to parameterized queries to avoid SQL Injection. It also helps in avoiding mistakes like missing a "'"
using (OleDbConnection connection =new OleDbConnection(connectionString))
{
var query = "Insert into Purchase (Invoice,VendorName,PurchaseDate,TotalAmt) values (#invoice,#vendor,#purchasedate,#amt)";
OleDbDataAdapter adapter = new OleDbDataAdapter(queryString, connection);
adapter.SelectCommand.Parameters.Add("#invoic", OleDbType.Integer).Value = Convert.ToInt32(Invoice_tx.Text);
adapter.SelectCommand.Parameters.Add("#vendor", OleDbType.VarChar,100).Value = VendorName_cb.Text;
adapter.SelectCommand.Parameters.Add("#invoic", OleDbType.Date).Value = PurchaseDate_dt.Value.Date; // I do not know what PurchaseDate_dt.Value.Date type is, so I leave it to you to convert to approapriate type
adapter.SelectCommand.Parameters.Add("#CategoryName", OleDbType.Integer).Value = Convert.ToInt32(TotalAmt_tx.Text);
connection.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}

Incorrect syntax near '(' when updating record in database

My code is producing an Incorrect syntax near '(' exception. I have tried two different ways but they both produce the same exception. I am trying to update a record in the database.
Here is my code and the line that produces the exception is the Execute non query line. The updater.Fill(dtable) which is commented out also produces the same exception.
protected void btnSave_Click(object sender, EventArgs e)
{
int found = 0; // No match found so far
// Get the current selected Manufacturer
string currentManufacturer = grdManufact.SelectedRow.Cells[1].Text;
string currentIsModerated = grdManufact.SelectedRow.Cells[3].Text;
// Connect to the database
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
SqlConnection conn = new SqlConnection(strConnectionString);
conn.Open();
// Try to find if new record would be a duplicate of an existing database record
if (txtManufactureName.Text != currentManufacturer)
{
string findrecord = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "'";
SqlDataAdapter adpt = new SqlDataAdapter(findrecord, conn);
DataTable dt = new DataTable();
found = adpt.Fill(dt);
}
if (found == 0) // New record is not a duplicate you can proceed with record update
{
String query;
if (checkBoxModerated.Checked)
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','true') WHERE ManufacturerName = " + currentManufacturer + ";";
}
else
{
query = "UPDATE VehicleManufacturer (ManufacturerName, ManufacturerDescription, Ismoderated) Values ('" + txtManufactureName.Text + "','" + txtDescription.Text + "','false') WHERE ManufacturerName = " + currentManufacturer + ";";
}
using (SqlCommand command = new SqlCommand(query, conn))
{
command.ExecuteNonQuery();
}
//using (SqlDataAdapter updater = new SqlDataAdapter(command))
// {
// DataTable dtable = new DataTable();
// updater.Fill(dtable);
// }
txtMessage.Text = "Manufacturer record changed Successfully";
txtManufactureName.Text = "";
txtDescription.Text = "";
checkBoxModerated.Checked = false;
}
else
{ // Record is a duplicate of existing database records. Give error message.
txtMessage.Text = "Sorry, that manufacturer name already exists.";
}
}
You are using the incorrect syntax for UPDATE statements.
Instead of
UPDATE Table (Fields) VALUES (Values) WHERE ...
It should be
UPDATE Table SET Field1=Value1, Field2=Value2 WHERE ...
Additionally, you have a SQL injection vulnerability (although this is not the reason for your exception).
Do not use string concatenation for SQL queries with user input. Use prepared statements instead.
Try this approach , it's safer also:
var isModerated = checkBoxModerated.Checked ; //true or false
//var isModerated = (checkBoxModerated.Checked)? 'true' : 'false' ;
command.Text = "UPDATE VehicleManufacturer
SET ManufacturerName = #manufacturerName,
ManufacturerDescription = #manufacturerDescription,
IsModerated = #isModerated
WHERE ManufacturerName = #manufacturer_name";
command.Parameters.AddWithValue("#manufacturerName", txtManufactureName.Text);
command.Parameters.AddWithValue("#manufacturerDescription", txtDescription.Text);
command.Parameters.AddWithValue("#isModerated", isModerated);
command.Parameters.AddWithValue("#manufacturer_name", txtManufactureName.Text);
command.ExecuteNonQuery();

Unable to fetch nvarchar type data with where clause in SQL Server 2008

string constr = Properties.Settings.Default.Subject_1ConnectionString;
SqlConnection conn = new SqlConnection(constr);
SqlCommand com = new SqlCommand("SELECT * from Subject_Title WHERE Date BETWEEN #hello and #hello1 ", conn);
// com.Parameters.Add("#hello", SqlDbType.NVarChar).Value = textBox1.Text;
// com.Parameters.Add("#hello1", SqlDbType.NVarChar).Value = textBox2.Text;
com.Parameters.Add("#hello", SqlDbType.NVarChar);
com.Parameters["#hello"].Value = textBox1.Text;
com.Parameters.Add("#hello1", SqlDbType.NVarChar);
com.Parameters["#hello1"].Value = textBox2.Text;
// com.Parameters.AddWithValue("#hello", textBox1.Text);
// com.Parameters.AddWithValue("#hello1", textBox2.Text);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "Subject_title");
for (int i = 0; i < 8; i++)
{
this.labeltext = this.labeltext + " " + ds.Tables["Subject_Title"].Rows[i]["Date"].ToString();
this.labeltext = this.labeltext + " " + ds.Tables["Subject_Title"].Rows[i]["Subject"].ToString();
this.labeltext = this.labeltext + " ";
}
this.label1.Text = this.labeltext;
Here I'm not getting any data from the database
Date is my column name with a nvarchar type, and Subject is another column of type text.
Pls anyone solve my problem
I guess you should use:
Con.Open();
Con.Close();
But if I were you I would have written this code like this:
string constr = Properties.Settings.Default.Subject_1ConnectionString;
SqlConnection conn = new SqlConnection(constr);
SqlCommand com = new SqlCommand("SELECT * from Subject_Title WHERE Date BETWEEN \"01-03-14\" and \"01-04-14\" ", conn);
conn.Open();
SqlDataReader reader =com.ExecuteReader();
while(reader.read()){
this.labeltext += " " + reader.GetString(0); //Use column ordinal for Date
this.labeltext += " " + reader.GetString(1)+" "; //Use column ordinal for Subject
}
conn.Close()
this.label1.Text = this.labeltext;
I tried to come up with a better code base for you.
You need to:
use more meaningful names! Parameters like hello and hello1 aren't very useful to someone reading your code.... also: don't name your columns with reserved keywords like Date - again: use something more meaningful to your context
if you want to use date-related methods, you must use DATE or DATETIME2(N) datatypes. If you have stored your data as nvarchar - you must convert it first to a DATE
please always put your SqlConnection and SqlCommand into using(...) { .. } blocks to ensure proper and speedy disposal
if you only need a single DataTable - just instantiate a DataTable and fill it - don't use the unnecessary additional overhead of a DataSet - that's just wasted resources...
Code:
string constr = Properties.Settings.Default.Subject_1ConnectionString;
// if you only need one single data table - use a DataTable - not a DataSet !
DataTable dt = new DataTable();
// *ALWAYS* put your SqlConnection and SqlCommand into using() blocks!
// also - if you want to use BETWEEN, you *MUST* use DATE!
// also: don't call your column "date" - that's a SQL Server reserved keyword! Use a more meaningful name
// like "DateCreated" or "DateLastUpdated" or something
// and please also use more meaningful parameter names - "hello" and "hello1" is very confusing and not clear!!
using (SqlConnection conn = new SqlConnection(constr))
using (SqlCommand com = new SqlCommand("SELECT * FROM dbo.Subject_Title WHERE CAST(DateCreated AS DATE) BETWEEN #start and #end ", conn))
{
// add parameters as DATE type!
com.Parameters.Add("#start", SqlDbType.Date);
com.Parameters["#start"].Value = DateTime.Parse(textBox1.Text).Date;
com.Parameters.Add("#end", SqlDbType.Date);
com.Parameters["#end"].Value = DateTime.Parse(textBox2.Text).Date;
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
}
for (int i = 0; i < 8; i++)
{
this.labeltext = this.labeltext + " " + dt.Rows[i]["Date"].ToString();
this.labeltext = this.labeltext + " " + ds.Rows[i]["Subject"].ToString();
this.labeltext = this.labeltext + " ";
}
this.label1.Text = this.labeltext;

Wildcards in T-SQL LIKE vs. ASP.net parameters

In my SQL statement I use wildcards. But when I try to select something, it never select something. While when I execute the query in Microsoft SQL Server Management Studio, it works fine.
What am I doing wrong?
Click handler
protected void btnTitelAuteur_Click(object sender, EventArgs e)
{
cvalTitelAuteur.Enabled = true;
cvalTitelAuteur.Validate();
if (Page.IsValid)
{
objdsSelectedBooks.SelectMethod = "getBooksByTitleAuthor";
objdsSelectedBooks.SelectParameters.Clear();
objdsSelectedBooks.SelectParameters.Add(new Parameter("title", DbType.String));
objdsSelectedBooks.SelectParameters.Add(new Parameter("author", DbType.String));
objdsSelectedBooks.Select();
gvSelectedBooks.DataBind();
pnlZoeken.Visible = false;
pnlKiezen.Visible = true;
}
}
In my Data Access Layer
public static DataTable getBooksByTitleAuthor(string title, string author)
{
string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.GENRE "
+ "FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID "
+"WHERE (tblBooks.TITLE LIKE '%#title%');";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString());
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = title;
DataSet ds = new DataSet();
da.Fill(ds, "Books");
return ds.Tables["Books"];
}
Try this:
string sql = "SELECT 'AUTHOR' = tblAuthors.FIRSTNAME + ' ' + tblAuthors.LASTNAME, tblBooks.*, tblGenres.GENRE "
+ "FROM tblAuthors INNER JOIN tblBooks ON tblAuthors.AUTHOR_ID = tblBooks.AUTHOR_ID INNER JOIN tblGenres ON tblBooks.GENRE_ID = tblGenres.GENRE_ID "
+"WHERE (tblBooks.TITLE LIKE #title);";
SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString());
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = "%" + title + "%";
You can't include your query parameter inside a string literal. Do it like this instead:
WHERE (tblBooks.TITLE LIKE '%' + #title + '%');
Also, whenever you have a leading wildcard you should look into a full text index instead. Your query as written is doomed to be much slower than it could be, because you can't use index when you have a leading wild card.
The answer from John Allers is correct. As an aside, you should wrap the SqlDataAdapter in a using block:
using (SqlDataAdapter da = new SqlDataAdapter(sql, GetConnectionString()))
{
da.SelectCommand.Parameters.Add("#title", SqlDbType.Text);
da.SelectCommand.Parameters["#title"].Value = title;
DataSet ds = new DataSet();
da.Fill(ds, "Books");
return ds.Tables["Books"];
}

Datagrid filter in c# using sql server

How to filter data in datagrid for example if you select the combo box in student number then input 1001 in the text field. All records in 1001 will appear in datagrid. I am using sql server
private void button2_Click(object sender, EventArgs e)
{
if (cbofilter.SelectedIndex == 0)
{
string sql;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds1 = new DataSet();
ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
sql = "Select * from Test where STUDNO like '" + txtvalue.Text + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds1);
dbgStudentDetails.DataSource = ds1;
dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
dbgStudentDetails.Refresh();
}
else if (cbofilter.SelectedIndex == 1)
{
//string sql;
//SqlConnection conn = new SqlConnection();
//conn.ConnectionString = "Server= " + Environment.MachineName.ToString() + #"\; Initial Catalog=TEST;Integrated Security = true";
//SqlDataAdapter da = new SqlDataAdapter();
//DataSet ds1 = new DataSet();
//ds1 = DBConn.getStudentDetails("sp_RetrieveSTUDNO");
//sql = "Select * from Test where Name like '" + txtvalue.Text + "'";
//SqlCommand cmd = new SqlCommand(sql,conn);
//cmd.CommandType = CommandType.Text;
//da.SelectCommand = cmd;
//da.Fill(ds1);
// dbgStudentDetails.DataSource = ds1;
//dbgStudentDetails.DataMember = ds1.Tables[0].TableName;
//ds.Tables[0].DefaultView.RowFilter = "Studno = + txtvalue.text + ";
dbgStudentDetails.DataSource = ds.Tables[0];
dbgStudentDetails.Refresh();
}
}
It's difficult to answer pricisely to a vague question. I guess that you'll have to adapt your SQL query with a WHERE statement containing the user input.
If 'student number' is selected in the combo box, query like this (numbers starting with):
SELECT id, name, number FROM students WHERE number LIKE #search + '%'
If 'student name' is selected, use another query (names containing):
SELECT id, name, number FROM students WHERE name LIKE '%' + #search + '%'
Please explain in what sense C# is concerned.
You don't say what is wrong with the code you commented out. You also don't say what type the Studno column is.
Have you tried something like:
ds1.Tables[0].DefaultView.RowFilter = "Studno = '" + txtvalue.text + "'";

Categories