POS system SQL query for cart display C# - c#

I am developing a POS system for a stationary. I am currently stuck in the sales page. I want to add to data grid view a product when user inputs barcode, quantity, discount and client id and this is the error I am getting:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'transaction'
string query;
string query2;
using (SqlConnection sqlcon2 = new SqlConnection(cons))
{
query = "insert into dbo.transaction set (qte,remise,idclt) values ('" + textBox4.Text + "','" + comboBox1.Text + "','" + textBox6.Text + "')";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon2);
}
using (SqlConnection sqlcon = new SqlConnection(cons))
{
sqlcon.Open();
query2 = "select produit.idprod, produit.nom_produit, transaction.qte, transaction.remise, transaction.idclt, transaction.qte*produit.prixV as Total from [dbo].[produit] join [dbo].[transaction] on produit.idprod=transaction.idprod join [dbo].[clients] clt on clt.idclt=transaction.idclt where produit.idprod= '" + textBox4.Text+"' and transaction.qte='"+textBox5.Text+"'";
SqlDataAdapter sda2 = new SqlDataAdapter(query2, sqlcon);
DataTable dt = new DataTable();
sda2.Fill(dt);
dgv.DataSource = dt;
}
Database Schema:
Form Design:

Hello and welcome to Stack Overflow.
It's highly likely that the problem in your code is the table's name being transaction, a keyword in the RDBMS you are using (as evidenced by the exception's message). Try to change it to something else.
In addition, your snippet is vulnerable to an SQL injection attack. Unless your project is well into development, you should consider using an ORM framework like Entity Framework Core.

Related

Can't write to SQLite database in WPF project

Having one of those tear-your-hair-out evenings.
I'm porting a WPF project over from using access and OleDBConnection to using SQLite and SQLiteConnection. My application reads from the project upon load, and then writes to it later after some form entry.
The reading works fine, using this code:
private void InitialiseDB()
{
connString = "data source = PortalDB.db";
conn = new SQLiteConnection(connString);
SQLiteCommand AttendeeCmd = new SQLiteCommand("SELECT * FROM AttendeeNames", conn);
SQLiteCommand SignInOutsCmd = new SQLiteCommand("SELECT SignTime, UserID, SignType FROM SignInOuts", conn);
conn.Open();
SQLiteDataAdapter AttendeeAdapter = new SQLiteDataAdapter(AttendeeCmd);
SQLiteDataAdapter SignInOutsAdapter = new SQLiteDataAdapter(SignInOutsCmd);
//Clear current datatables
AttendeeNamesTable.Clear();
SignInOutsTable.Clear();
//Fill data tables from adapters
AttendeeAdapter.Fill(AttendeeNamesTable);
SignInOutsAdapter.Fill(SignInOutsTable);
conn.Close();
}
But for the life of me I can't get the writing to work, It doesn't throw any errors or exceptions, it just doesn't write to the database. That code looks like this, with the data being passed in from having just been aded to a local DataTable:
private void SyncUpDB(int SignUserId, string SignType, DateTime SignTime)
{
//...Open the connection...
conn.Open();
//..Make SQL query by declaring fields to write to (not SignID) and where to get the data from. Strings need single quote, numbers do not.
String SyncUpDBQuery = "INSERT INTO SignInOuts (SignTime,UserID,SignType) VALUES('" + SignTime + "', " + SignUserId + ", '" + SignType + "')";
//...Make new database command from query
SQLiteCommand SyncUpDBCommand = new SQLiteCommand(SyncUpDBQuery, conn);
//...And execute on database
SyncUpDBCommand.ExecuteNonQuery();
}
As I say, this used to work perfectly with Access, just won't play ball with SQLite... any ideas?

Display data in 2 tables in one crytal report in c#

I am trying to display some data on crystal report. after written the code the issued part of the report displayed well while the receiving part displayed only the first data within the range selected and duplicated several times. here is the code below
public DataSet itembincardreport(string date1, string date2, string
itemcode)
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = null;
Connection cs = new Connection();
con = new SqlConnection(cs.DBcon);
con.Open();
DataSet ds = new DataSet();
frmReport frm = new frmReport();
string sql = "select * from ISSUED, RECEIVED WHERE
ISSUED.ITEMCODE=RECEIVED.ITEMCODE AND ISSUED.ITEMCODE = '" + itemcode + "'
AND RECEIVED.ITEMCODE = '" + itemcode + "' and ISSUED.TRANSDATE
between '" + Convert.ToDateTime(date1) + "' and '" +
Convert.ToDateTime(date2) + "' and RECEIVED.TRANSDATE between '" +
Convert.ToDateTime(date1) + "' and '" + Convert.ToDateTime(date2) + "'";
SqlDataAdapter dadbt = new SqlDataAdapter(sql, mycon.DBcon);
dadbt.Fill(ds);
dadbt.Dispose();
return ds;
}
The root cause of your problem is the query. Whether the received and issued tables have multiple rows that match each other or not, I cannot say (you need to post some better example table data than the screenshot given) but your query in the string should be written like this:
string sql =
#"select *
from
ISSUED
inner join
RECEIVED
on
ISSUED.ITEMCODE=RECEIVED.ITEMCODE -- this is probably the fault
-- try joining on ISSUEDID = RECEIVED instead??
where
ISSUED.ITEMCODE = #itemcode and
ISSUED.TRANSDATE between #date1 and #date2 and
RECEIVED.TRANSDATE between #date1 and #date2";
Later in your code, you should call:
var c = new SqlCommand();
c.CommandText = sql;
c.Connection mycon;
c.Parameters.AddWithValue("#itemcode", itemcode);
c.Parameters.AddWithValue("#date1", Convert.ToDateTime(date1)); //you should make the method argument a DateTime
c.Parameters.AddWithValue("#date2", Convert.ToDateTime(date2)); //you should make the method argument a DateTime
SqlDataAdapter dadbt = new SqlDataAdapter(c);
That's how to PROPERLY do database queries with parameters.. Now whether there are duplicate rows or not is purely down to your table data*, but at least your SQL is immune from hackers putting an itemcode of '; DROP table issued; -- in and screwing up your world
*post some detailed example data if you want help with that and I'll edit this answer. Take a look at SQLFiddle.com

Insert command works without errors in C# but data is not inserted to the MS SQL Server

I am trying to insert data into Microsoft SQL Server DB using C# and the insert command works well and I get no errors or exceptions. But when I check my database in SQL Server there is no effect on the table and the records are not inserted into the table. This is the code that I try:
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "')";
con1.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
continue;
}
I've seen similar questions here and here, but the answers did not fix my problem.
Also when I insert data to the DB manually and run select command like mentioned below, I get the correct answer but for the insert command I do not.
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con2.Open();
SqlDataAdapter da1 = new SqlDataAdapter("select * from Users where ChatID='" + update.Message.Chat.Id.ToString() + "'", con2);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
con1.Close();
Please help me fix this issue.
By the way I know that this kind of insertion is not safe and I'l like to let you know that this is just a demo and I will make it secure against sql injection.
You are not executing your command anywhere.
You need:
cm1.ExecuteNonQuery();
In your code, you are creating a SqlCommand object, then you associate a SqlConnection to it, but in no where you are actually executing the command. Your code should look like:
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "Server = (local); Database = My_DataBase; Integrated Security = true";
con1.Open();
SqlCommand cm1 = new SqlCommand();
cm1.Connection = con1;
cm1.CommandText = "insert into Users values('" + update.Message.Chat.Id.ToString() + "','" + update.Message.Chat.FirstName + "','" + update.Message.Chat.LastName + "','#" + update.Message.Chat.Username + "','" + req1.Status + "'";
cm1.ExecuteNonQuery();
con1.Close();
Apart from SQL Injection vulnerability, you should consider enclosing your SqlCommand and SqlConnection object in using statement, that will ensure proper disposal of un-managed resources.

C# WPF mysql string

I'm creating a wpf app that is connected to localhost database, it has 2 tables, now I ran into an error but I'm not sure what is wrong in the code. Can anyone help?
I'm getting this error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'
occurred in MySql.Data.dll
Additional information: You have an error in your SQL syntax; check
the manual that corresponds to your MariaDB server version for the
right syntax to use near 'left join author on
book.author_id=author.id' at line 1
private void Filter_TextChanged(object sender, TextChangedEventArgs e)
{
connection.Open();
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM book where book.name like ('" + Filter.Text + "%') left join author on book.author_id=author.id";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
_dataView = new System.Data.DataView(dt);
_dataView.Sort = "name ASC,id ASC";
BooksGrid.DataContext = dt;
connection.Close();
}
Change your query to
cmd.CommandText = "SELECT * FROM book left join author on book.author_id=author.id where book.name like ('" + Filter.Text + "%') and book.author_id=author.id";
The additional "book.author_id=author.id" clause at the end is to ensure that you only get records that match on author_id.
Also instead of cmd.ExecuteNonQuery(), you should try and use the cmd.ExecuteReader() since you are retrieving rows.

error in c# :One Or More Error Messages Occurred During Processing Of Command

this is my code:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=MSDAORA;Data Source=data;Password=ss8_pakhsh;User ID=SHIFTS_N";
con.Open();
int MAXID = 1175;
MAXID++;
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(" + MAXID + ",'"
+ textBox1.Text +
"', SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME="+comboBox1.Text;
OleDbDataAdapter oda = new OleDbDataAdapter(sqlcommand, con);
oda.Fill(dt);
con.Close();
while i running it ,gets this error :
One or more errors occurred during processing of command.
i think my query has problem because when i enter it on TOAD editor(for oracle) gets me this error:
ORA-00936: missing expression
You were missing quotes and paranthesis in your query.
SQL Injection Alert
To avoid this you should use Parameterized queries as like follows
string sqlcommand ="INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID)
VALUES(?,?,SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME=?)";
OleDbConnection oledbConnection = new OleDbConnection(con);
OleDbCommand oledbCommand = new OleDbCommand(sqlcommand , oledbConnection);
oledbCommand.Parameters.AddWithValue("?", txtquotationno.Text);
oledbCommand.Parameters.AddWithValue("?", cmbjobcode.Text);
oledbCommand.Parameters.AddWithValue("?", comboBox1.Text);
OleDbDataAdapter oda = new OleDbDataAdapter(oledbCommand);
DataTable dt= new DataTable();
oda.Fill(dt);
You need to put your select query in braces as you are selecting this from another table so this shoould be in (). Also Department_Name looks of type varcharso its value should be in single quotes. Change your query like this.
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(" + MAXID + ",'"
+ textBox1.Text +
"',(SELECT DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE DEPARTMENT_NAME='"+comboBox1.Text+"'"));
Also use parameterized query to prevent sql injection.

Categories