I'm getting a "syntax error" while using the code below.
it suppoused to avoid adding row when you entered all the values of this specific protein(it is a project combined Biology and Programming.
'serialPro' is a textbox which contains a number,but saved as string.
'Reset_Click' resetes all textboxes.
THE CODE:
if ((serialPro.Text == String.Empty) || (codon1.Text == String.Empty))
{
MessageBox.Show("You didn't fill all the fields","Attention"
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
Reset_Click(sender, e);
}
else
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();
string mySQL = " SELECT COUNT(tblOrderAA.orderAASerialPro) AS orderAASerialPro1 FROM tblOrderAA" +
"WHERE tblOrderAA.orderAASerialPro=" + Convert.ToInt32(serialPro.Text) +
" SELECT (tblProInfo.proInfoSerialNum) FROM tblProInfo WHERE tblProInfo.proInfoSerialNum=" +
Convert.ToInt32(serialPro.Text);
OleDbCommand datacommand = new OleDbCommand(mySQL, myConnection);
OleDbDataReader dataReader = datacommand.ExecuteReader();
dataReader.Read();
if (dataReader.GetInt32(0) == dataReader.GetInt32(1))
{
MessageBox.Show("You have entered all the amino acids for this protein", "Attention",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
Reset_Click(sender, e);
}
TNX for the help!
I'm not sure if having two select statements in your MySQL query is valid or not, or why you're taking a string only to turn it into a number so you can add it to another string, but this is probably the cause of the syntax error.
" SELECT COUNT(tblOrderAA.orderAASerialPro) AS orderAASerialPro1 FROM tblOrderAA" +
"WHERE tblOrderAA.orderAASerialPro=" + Convert.ToInt32(serialPro.Text) +
The way you're concatenating this string means there would be no space between tblOrderAA and WHERE. Add a space in between.
You should also look up SQL injection/parameterized queries.
First, the way you have it setup, even if it were supported by access, would require you to process different resultset (you would have to call Reader.NextResult in order to get the values from the second select statement.
However, this is an easy problem to solve: break your queries up into separate commands and just get the one value from each query that you are looking for:
int TotalCompleted;
int TotalToComplete;
string mySQL;
OleDbCommand datacommand;
object oValue;
mySQL = " SELECT COUNT(tblOrderAA.orderAASerialPro) AS orderAASerialPro1 FROM tblOrderAA WHERE tblOrderAA.orderAASerialPro=" + Convert.ToInt32(serialPro.Text);
datacommand = new OleDbCommand(mySQL, myConnection);
oValue = datacommand.ExecuteScalar();
if (oValue != DBNull.Value)
{
TotalCompleted = (int)oValue;
} else
{
TotalCompleted = 0;
}
mySQL = "SELECT tblProInfo.proInfoSerialNum FROM tblProInfo WHERE tblProInfo.proInfoSerialNum=" + Convert.ToInt32(serialPro.Text);
datacommand = new OleDbCommand(mySQL, myConnection);
oValue = datacommand.ExecuteScalar();
if (oValue != DBNull.Value)
{
TotalToComplete = (int)oValue;
} else
{
TotalToComplete = 0;
}
if (TotalCompleted == TotalToComplete)
{
MessageBox.Show("You have entered all the amino acids for this protein", "Attention",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
Reset_Click(sender, e);
}
Related
I want to know if it is possible to create a query like that:
SELECT :parameterA, :paramaterB
FROM *someTable*;
The idea is to use some structure like that instead of making some sort of string or something like that.
I´m working with SQL database and a C# project in Visual Studio 2019.
So far I have this code:
public List<V_Requerimientos> GetData(int idEmpresa, string columns)
{
List<V_Requerimientos> result = null;
try
{
var dyParam = new OracleDynamicParameters();
dyParam.Add("idEmpresa", OracleDbType.Int32, ParameterDirection.Input, value: idEmpresa);
var conn = this.GetConnection();
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
if (conn.State == ConnectionState.Open)
{
string query = "SELECT " + columns + "FROM V_REQUERIMIENTOS " +
"WHERE EMPR_CODIGO = :idEmpresa AND ETAR_CODIGO <> 4";
result= conn.Query<V_Requerimientos>(query, dyParam).ToList();
conn.Close();
}
}
catch (Exception e)
{
throw e;
}
return result;
}
where idEmpresa is the PK of the object selected in the front, and columns is a string which contains the columns I want to select for that object.
I was wondering if there is anyway for replace columns for parameters sent to the method instead of using the concatenated query as I have at the moment.
SQL parameters are used to specify value in the where clause. You would not use parameters for column names. Your query should look more like this.
string colA = "Customer Id";
string colB = "Customer Name";
string sql = $"Select [{colA}], [{colB}] from table";
My Code For Searching Data In SQL Server Compact Database is not working please review my code. any help will be greatly appreciated.
#region btnSearch_Click
private void btnSearch_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection("Data Source="
+ System.IO.Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Database.sdf"));
sda = new SqlCeDataAdapter();
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string sql = "select Name from tblCustomers ";
if (tbSearch.Text.Length > 0)
{
sql += "where Name like " + tbSearch.Text + " % ";
}
try
{
SqlCeCommand cmd = new SqlCeCommand(sql, con);
cmd.CommandType = CommandType.Text;
// if you don’t set the result set to
// scrollable HasRows does not work
SqlCeResultSet rs = cmd.ExecuteResultSet(
ResultSetOptions.Scrollable);
if (rs.HasRows)
{
int Name = rs.GetOrdinal("Name");
// Hold the output
StringBuilder output = new StringBuilder();
// Read the first record and get it’s data
rs.ReadFirst();
output.AppendLine(rs.GetString(Name)
+ " " + rs.GetString(Name));
while (rs.Read())
{
output.AppendLine(rs.GetString(Name)
+ " " + rs.GetString(Name));
}
// Set the output in the label
lblResults.Text = output.ToString();
}
else
{
lblResults.Text = "No Rows Found.";
}
}
catch (SqlCeException sqlexception)
{
MessageBox.Show(sqlexception.Message, "Error.",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error.",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
#endregion
it's throwing the bellow exception.
There was an error parsing the query. [ Token line number = 1,Token line offset = 53,Token in error = % ]
A useful way to solve such issues is to view the SQL string generated by your code right before sending it to SQL Server. If you can spot the problem immediately, that's great - fix it. If you can't try running the full query directly with the SQL Server Management Studio and see if you understand the problem. If you still can't post this query as a question on a Q&A site (just like here on SO) and it will be much easier to help you.
In this case, it looks to me like you're missing single quotes around the value ("like 'text'") - but I can't be sure cause it depends on the value of tbSearch.Text.
I have a form which displays selected datagridviewrow data in textboxes. I would like to edit and update the data from this form and update and save into the datatable when the user clicks update.
When I click update I get an error message:
There was an error parsing the query. [ Token line number = 1,Token line offset = 25,Token in error = ( ]
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
UpdateDataBase();
editBTN.Text = "Edit";
deleteBTN.Visible = true;
notEditable = true;
}
else
{
deleteBTN.Visible = false;
editBTN.Text = "Update";
deleteBTN.Visible = false;
notEditable = false;
}
firstTxt.ReadOnly = notEditable;
surenameTxt.ReadOnly = notEditable;
address1Txt.ReadOnly = notEditable;
address2Txt.ReadOnly = notEditable;
countyTxt.ReadOnly = notEditable;
contactTxt.ReadOnly = notEditable;
emailTxt.ReadOnly = notEditable;
postTxt.ReadOnly = notEditable;
}
private void UpdateDataBase()
{
if (MessageBox.Show("Customer information will be updated. This change cannot be undone. Are you sure you want to continue? ", "Confirm Edit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "update customersTBL set ([First_Name] = '" + this.firstTxt.Text + "',surename= '" + this.surenameTxt.Text + "',[Address Line 1] = '" + this.address1Txt.Text + "',[Address Line 2] = '" + this.address2Txt.Text + "',County = '" + this.countyTxt.Text + "',[Post Code] = '" + this.postTxt.Text + "' , Email = '" + this.emailTxt.Text + "';,[Contact Number] = '" + this.contactTxt.Text + "');";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Customer information has been updated", "Update Sucessful");
while (myReader.Read())
{
}
MessageBox.Show("Please exit the Customers window and re-open to update the table");
this.Close();
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
There are some problems in your code.
One is trivial and could be easily fixed (remove the semicolon before the [Contact Number], but there are other hidden problems that potentially are more serious.
First: Remember to always close and dispose the disposable objects
(connection and command in this case). The using statement ensure
that the object enclosed by the using block will be correctly closed
and disposed also in case of exceptions
Second: Use a parameterized query. This avoids Sql Injections and
parsing problems. If one or more of your input data contains a single
quote, the string concatenation used to build the sql command text
will resul in an invalid command
Third: An update command acts on all the records present in the table
if you don't add a WHERE condition. Usually the WHERE condition is
added to identify the only record that need to be updated and it is
the value of a field with UNIQUE index or the PRIMARY KEY of your
table. Of course you could update more than one record with a less
restrictive WHERE clause but this doesn't seem to be the case
Fourth: Use the ExecuteNonQuery instead of ExecuteReader for commands
that update/insert the database (well it works equally but why use a
method that should be reserved for other uses?)
private void UpdateDataBase(int customerID)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = #"update customersTBL set [First_Name] = #fname,
surename = #sur, [Address Line 1] = #addr1,
[Address Line 2] = #addr2, County = #county,
[Post Code] = #pcode, Email = #mail, [Contact Number] = #ctNo
WHERE customerID = #id";
using(SqlCeConnection conDataBase = new SqlCeConnection(constring))
using(SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cndDataBase.Parameters.AddWithValue("#fname", this.firstTxt.Text);
cndDataBase.Parameters.AddWithValue("#sur", this.surenameTxt.Text );
cndDataBase.Parameters.AddWithValue("#addr1", this.address1Txt.Text );
cndDataBase.Parameters.AddWithValue("#addr2", this.address2Txt.Text );
cndDataBase.Parameters.AddWithValue("#county", this.countyTxt.Text );
cndDataBase.Parameters.AddWithValue("#pcode", this.postTxt.Text );
cndDataBase.Parameters.AddWithValue("#mail", this.emailTxt.Text );
cndDataBase.Parameters.AddWithValue("#ctNo", this.contactTxt.Text );
cndDataBase.Parameters.AddWithValue("#id", customerID );
int rowsUpdated = cmdDataBase.ExecuteNonQuery();
if(rowsUpdate == 0)
MessageBox.Show("No customer found to update");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
As you can see, with a parameterized query is more difficult to write a bad sql text with hidden problems and the quoting job is passed to the database code that knows better how to format the parameter values.
The only problem that you need to solve is how to retrieve the value for the customerID or some other value that you could use in the WHERE clause to uniquely identify the record of your customer
In this point you call the UpdateDatabase method that now required a UserID variable containing the key to identify your user on the table
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
// Here you need to identify uniquely your modified user
// Usually when you load the data to edit you have this info extracted from your
// database table and you have saved it somewhere
// (of course the user should not edit in any way this value
int UserID = ... ???? (from an hidden textbox? from a global variable, it is up to you
UpdateDataBase( UserID );
I think your confusing the Update structure with an Insert.
For your update it looks like this:
update customersTBL set ([First_Name] = 'data', surename= '',[Address Line 1] = '',[Address Line 2] = '',County = '',[Post Code] = '' , Email = '';,[Contact Number] = '');
You need a where clause.
Update/Set does not put the changes in ()
After email you have a ';'
Hi Believe the problem is with the C# code itself and not the SQL statement, as I have outputted the SQL to the screen and run it direct into the database.
For example
SELECT COUNT(*)
FROM meeting_room.meeting_acceptance
WHERE meeting_id = 'AAMkADY3MDk3NTdiLTE4M2ItNDk4ZS1hNmZjLWJmMDhkYTBiMDVjYgBGAAAAAAB+oqKzNnIvRZgdzn8wIE0XBwC62mlG2pRhSKvV6Bc2NH7rAAAALqU/AAC62mlG2pRhSKvV6Bc2NH7rAAAp5DTDAAA=';
Returns 1, although when outputting the "NoRows" variable, 0 still appears, any ideas?
if ((Appoint.End > DateTime.Now) && (Appoint.Start < DateTime.Now))
{
MySql.Data.MySqlClient.MySqlConnection mycon3 = new MySqlConnection(GetConnectionString());
if (mycon3.State != ConnectionState.Open)
try
{
mycon3.Open();
}
catch (MySqlException ex)
{
throw (ex);
}
using (mycon3)
sql = "SELECT count(*) from meeting_room.meeting_acceptance where meeting_id = '" + Appoint.Id + "';";
Label1.Text = sql;
using (MySqlCommand mcmd = new MySqlCommand(sql, mycon3))
try
{
using (MySqlDataReader datareader = mcmd.ExecuteReader())
{
while (datareader.Read())
{
NoRows = Convert.ToInt32(datareader.GetValue(0));
}
}
}
catch
{
Error.Text = "SQL Exception 2" ;
sqlerror = true;
}
Success.Text = NoRows.ToString();
if ( NoRows == 0 )
{
ConfirmLink.Text = "<div align=\"center\"><img src=\"Confirm.jpg\" alt=\"confirm\" /></div>";
if (DateTime.Now.AddMinutes(-2) > Appoint.Start)
{
Error.Text = "Would have deleted meeting";
// Appoint.CancelMeeting("The meeting you created for the " + resource_name + " on " + Appoint.Start + " Subject: " + Appoint.Subject + " has been deleted as you did not accept the meeting");
}
}
}
You need to use ExecuteScalar method
int count = (int) (mcmd.ExecuteScalar() ?? 0);
Also you have not enclosed the using block properly..Your code should look like
using(MySqlConnection mycon3 = new ....)
{
try
{
mycon3.Open();
//your commands
}
catch(SqlException e){}
}
Also your query is vulnerable to sql injection attack..Consider using SqlParameter
Convert.ToInt32(cmd.ExecuteScalar());
if you try to do explict conversion then it make a exception. Convert.ToInt32 will gave you 0 if result is null.
Your code doesn't use SQL-Parameter so it will be unsafe. use Sql parameter to make your code safer from Sql-injection.
what is wrong with this code what i am actually to achieve is
insert rows to database clear the textbox value and enter another record..
the problem is at first loop data will be added successfully...but on the next iteration loops it will add empty strings to the rows of database but what i want is accept input from textbox and continue iterating...please try to read the code and help me ...it is been 2 weeks since am trying so solve this ..
again what i want to do
-user enter number of group members
- the group members have column like ,first name,last name gender,city.etc
FOR all the group members (eg:6 group membrs) add 6 rows of of different column will be added
but my code does is add the first rows and the rest 5 row's will be empty data
Sorry for my bad english..somebody please try to think what i am thinking
{{
private void btnAddloan_Click(object sender, RoutedEventArgs e)
if (txtname.Text != "" && txtlname.Text != "")
{
int c=0;
int input=int.Parse(txttotalnumberofgroupmembers.Text);
do
{
string connstr = "Data Source=GER-PC\\PLEASEGOD;Initial Catalog=ACSI;Integrated Security=True";
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Customer(FirstName,LastName) values(#n,#p)", con);
cmd.Parameters.AddWithValue("#p", txtname.Text);
cmd.Parameters.AddWithValue("#n", txtlname.Text);
cmd.ExecuteNonQuery();
con.Close();
lblnotify.Content = c + 1 + "" + "members added";
//clear textbox values and wait for another input
txtname.Text = "";
txtlname.Text = "";
if (txtname.Text != "" && txtlname.Text != "")
{
continue;
}
else
{
MessageBoxResult result =MessageBox.Show("procces","Continue Adding Memebers",MessageBoxButton.YesNoCancel,MessageBoxImage.Warning);
//txtname.Text = s;
//txtlname.Text= s1;
//MessageBox.Show();
switch (result)
{
case MessageBoxResult.Yes:
if (txtname.Text != "")
{
}
else
{
}
break;
case MessageBoxResult.No:
break;
case MessageBoxResult.Cancel:
break;
}
}
c++;
} while (c < input);
}
else
{
MessageBox.Show("plese fill first name and last name");
}
}
You're clearing the txtname.Text and txtlname.Text value after you do the insert. In the next iteration you're recreating the Parameters, but this time your text values are EMPTY.
txtname.Text = "";
txtlname.Text = "";
Instead of recreating your command object, why not just execute the command object N times. Like:
SqlCommand cmd = new SqlCommand("insert into Customer(FirstName,LastName) values(#n,#p)", con);
cmd.Parameters.AddWithValue("#p", txtname.Text);
cmd.Parameters.AddWithValue("#n", txtlname.Text);
for(int i = 0; i < input; i++)
{
cmd.ExecuteNonQuery();
}