sql error - missing a (;) at the end of sql statement - sql

I'm trying to get this bit work but it keep saying that missing a (;) at the end of a SQL statement. Basically, this code will get filename of a picture and insert into photodatabase in fileName column, if the filename already exist then just update = 1.
INSERT INTO photoDB(fileNames)
VALUES('" + Path.GetFileName(fileName) + "')
ON DUPLICATE KEY UPDATE fileNames = 1

The error is message is quite clear. You need a semi-colon at the end of your SQL string (fileNames = 1;.

Here is an example that helps to protect against SQL injection and fixes your semi colon problem.
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO photoDB (fileNames) VALUES(#fileName) ON DUPLICATE KEY UPDATE fileNames = 1;";
command.Parameters.Add(new SqlParameter("#filename", System.Data.SqlDbType.VarChar).Value = Path.GetFileName(fileName));
command.ExecuteNonQuery();

Second answer (now that the OP has fixed the semi-colon issue).
Is this MySQL? Other databases will not support that ON DUPLICATE KEY syntax.
Your ON DUPLICATE KEY clause sets a TEXT column (fileNames) to an INTEGER value (1). Try putting quotes around the integer value.

Related

VB.NET Oracle SQL "INSERT INTO" with "RETURNING INTO" gives ORA-00933 Command Not Properly Ended

I need to update some code and as part of this I need to insert a row into a table and obtain the id (primary key) of the row just entered.
Have researched this and I believe I should be using RETURNING INTO and Oracle Parameters. I have used parameters in the past successfully to Insert values.
I have an INSERT statement that runs perfectly from VB.NET, but as soon as I add the text "" RETURNING id INTO :myId" I get ORA-00933 Command Not Properly Ended.
Here is a version of the code.
sql = "INSERT ... RETURNING id INTO :myId"
Connect()
Dim intRecsAffected As Integer = 0
Dim comm As OracleCommand = New OracleCommand(sql, _conn)
Dim param As OracleParameter
param = New OracleParameter()
param.ParameterName = ":myId"
param.OracleDbType = OracleDbType.Int32
param.Direction = ParameterDirection.Output ' Tried ReturnValue
comm.Parameters.Add(param)
intRecsAffected = comm.ExecuteNonQuery()
id = comm.Parameters(":myId").Value
Disconnect()
Any ideas?
I believe that your syntax is incorrect:
sql = "INSERT ... RETURNING id INTO myId"
Example below:
https://oracle-base.com/articles/misc/dml-returning-into-clause
Actually, realised what was going on. I cut my full SQL as it's quite long and there's some sensitive stuff in there.
The INSERT was using a SELECT rather than VALUES to get the values for the fields. That won't work - I am guessing because an INSERT with SELECT can add multiple rows even though in this case it won't.
Have re-written the SQL to use VALUES and the VB.Net code works fine.
Thanks to all who replied.

VB.net - How can I delete an Item in an Access Database?

I'm trying to delete an Item in my Access Database with vb.net
my code is:
Dim DString As String = "DELETE * FROM studentTable WHERE ID='" & DataGridView1.SelectedRows.Item(0).Cells(0).Value & "'"
Dim DCMD As New OleDbCommand(DString, con)
DCMD.ExecuteNonQuery()
Fill()
the code is working fine, my Problem is it's not working because my "ID" Row is set to AutoIncrement. What can I do to fix??
King regards
You have a syntax error in your SQL. You do not need a projection (column list) for a DELETE statement.
Try removing the * such as:
DELETE FROM studentTable WHERE ID=....
Also you do not need to quote numeric values with the apostrophe character (I don't think it will hurt).
You might also want to consider using a parameterized query instead of embedding the value.

how to insert data through VB.NET

I am trying to pass my query string into database using VB.NET, but I am seeing a syntax error. I don't know where it is, please help me!
Me.str = String.Concat(New String()
{"Insert into Sales values('",
Me.txtVoucherNo.Text, "','", dtpDate.Value, "','",
dtpMonth.Value, "','", POSPage.txtPatientNo.Text, "','",
POSPage.txtPatientName.Text, "','",
POSPage.txtAddress.Text, ",'--',", POSPage.txtsubtotal.Text, "','",
POSPage.txtTax.Text, ",'--',", POSPage.txtdiscount.Text, "','",
POSPage.txtGrandTotal.Text, "')"})
Nooooooooooooo!
String edits like that leave you vulnerable to sql injection attacks. It's practically begging to get hacked.
You want something more like this:
Using cn As New SqlConnection(" connection string here "), _
cmd As New SqlCommand(
"Insert into Sales VALUES ( #VoucherNo, #Date, #Month, #PatientNo, #PatientName, #Address, '--', #SubTotal, #Tax, '--', #Discount, #GrandTotal )"
, cn )
'change this to use the actual column types and lengths in your database
cmd.Parameters.Add("#VoucherNo", SqlDbType.NVarChar, 10).Value = Me.txtVoucherNo.Text
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = dtpDate.Value
cmd.Parameters.Add("#Month", SqlDbType.DateTime).Value = dtpMonth.Value
cmd.Parameters.Add("#PatientNo", SqlDbType.NVarChar, 10).Value = POSPage.txtPatientNo.Text
cmd.Parameters.Add("#PatientName", SqlDbType.NVarChar, 50).Value = POSPage.txtPatientName.Text
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 250).Value = POSPage.txtAddress.Text
cmd.Parameters.Add("#SubTotal", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtsubtotal.Text)
cmd.Parameters.Add("#Tax", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtTax.Text)
cmd.Parameters.Add("#Discount", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtdiscount.Text)
cmd.Parameters.Add("#GrandTotal", SqlDbType.Decimal).Value = Convert.ToDecimal(POSPage.txtGrandTotal.Text)
cn.Open()
cmd.ExecuteNonQuery()
End Using
Note that, with this code, the SQL string itself is constant. Instead of a string field in your class (Me.Str), you need the full SqlCommand object, so that you can hold both the sql statement and the parameter data.
If you still have trouble with this, try including the names of the columns before the VALUES() clause.
That out of the way, original syntax error was because of this sequence in your string array:
"','", POSPage.txtAddress.Text, ",'--',"
Note that this would open a quoted field in your query, but not close it until after the comma. What comes next is a comment marker in Sql Server. In short, if you actually enter the name of the field as the address, you'd get this:
'POSPage.txtAddress.Text,'--
Everything after the two hyphens would be commented out, including the closing parentheses for your VALUES clause, meaning the query is not valid SQL syntax... assuming someone hasn't already used sql injection on another field to include put whatever sql statement they want as part of the query.
I won't tell you how to just fix that error, because it should be obvious now, and well... there's that pesky injection problem again. I will say that you made the same mistake with the other ",'--'," string later in the query.

SQL Update Column By Adding A Number To Current Int

Simple enough, I can't figure out how to add (that's +) an integer from a textbox to the integer in the SQL Field.
So for example, the SQL Field may have '10' in it and the textbox may have '5' in it. I want to add these numbers together to store '15' without having to download the SQL Table.
The textbox that contains the integer to be added to the SQL integer is tranamount.Text and the SQL Column in the SQL Table is #ugpoints. Please note, without the '+' - which is in the below code and is admittedly wrong- the value of tranamount.Text is added to the Table without an issue, but it simply replaces the original value; meaning the end result would be '5' in the SQL Field.
What would be the proper way to structure this? I've tried the below code, but that clearly doesn't work.
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=#ugpoints WHERE Members_ID=#recevierID", con)
cmd.Parameters.AddWithValue("#recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("#ugpoints", + tranamount.Text) '<--- Value to add.
cmd.ExecuteNonQuery()
Newbies question I know, I'm new to SQL in vb.
You have to use the correct sql:
Dim sql = "UPDATE PersonsA SET U_G_Studio=U_G_Studio + #ugpoints WHERE Members_ID=#recevierID"
Also use the correct type with AddWithValue:
Using cmd = New SqlCommand(sql, con)
' use the using-statement to dispose everything that implements IDisposable, so also the connection '
cmd.Parameters.AddWithValue("#ugpoints", Int32.Parse(tranamount.Text))
' .... '
End Using
Take the current value of the U_G_Studio field, add the value of the parameter and reassign to U_G_Studio, but keep in mind that you need to pass the value as an integer because otherwise the AddWithValue will pass a string and you get conversion errors coming from the db.
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio=U_G_Studio + #ugpoints " &
"WHERE Members_ID=#recevierID", con)
cmd.Parameters.AddWithValue("#recevierID", tranmemberID.Text)
cmd.Parameters.AddWithValue("#ugpoints", Convert.ToInt32(tranamount.Text))
cmd.ExecuteNonQuery()
The SQL you want is:
"UPDATE PersonsA SET U_G_Studio= (U_G_Studio + #ugpoints) " & _
"WHERE Members_ID=#recevierID"
what about
cmd.Parameters.AddWithValue("#ugpoints", (int)tranamount.Text)
....
cmd = New SqlCommand("UPDATE PersonsA SET U_G_Studio= SET U_G_Studio + #ugpoints WHERE Members_ID=#recevierID", con)
edit1: STEVE WAS FASTER!

insert MSSQL more than 8000 characters in a nvarchar(max) field

While using sql 2005, it appears I am unable to insert more than 8000 characters in a nvarchar(max) field.
This is really puzzling. I have tried insert, update and update .write with no luck. I can't insert it completely in the console and in .net the error I consistently get is
The data types text and varchar are incompatible in the add operator.
The insert statement is
insert into tablename (columnname) values (' long text');
Update:
update tablename set columnname='long text'
Everything is always truncated at 8000 characters (the text is 11,000 characters). Running a few tests, I see that
select ##textsize
gives 2147483647
Any ideas what I might be doing wrong here?
Your code truncates the value somewhere. You did not include the entire code, so we cannot guess where it truncates. The usual place is parameter declarations. The correct code should be like this:
SqlCommand cmd = new SqlCommand(
#"insert into table (column) values (#param)", conn, trn);
cmd.Paramaters.Add("#param", SqlDbType.NVarChar, -1);
cmd.Parameters["#param"].Value = myLongVariable;
cmd.ExecuteNonQuery();
using (System.Data.SqlClient.SqlConnection con = new
SqlConnection("YourConnection string"))
{
con.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
{
string expression = "long text.................................";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your long text Parameter Name ",
SqlDbType.NVarChar).Value = expression;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
I've just had this issue and eventually tracked it down to the ADO constant I was using in the VBA code that calls the stored procedure. Originally I was adVarChar which gave me the "String data, right truncation" message, but when I swapped this out for adLongVarChar it now works fine
cmd.Paramaters.Add("#param", SqlDbType.NVarChar, -1).Value=parametervaluehere;
where -1 means max length for varchar/nvarchar datatype.