Im trying to insert data to my compact database, I got this error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = USE ]
And here is my code, mostly found online:
SqlCeConnection conn = new SqlCeConnection(#"Data Source=|DataDirectory|\CompactDatabase.sdf");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "USE Movie INSERT INTO Movie(title, ean) VALUES(?,?)";
cmd.Parameters.AddWithValue("#title", title);
cmd.Parameters.AddWithValue("#ean", ean);
cmd.Prepare();
cmd.ExecuteNonQuery();
Anyone figure out the problem?
Anyone figure out the problem?
Just throw away USE clause and execute this query instead:
INSERT INTO Movie(title, ean) VALUES(?,?)
USE is a context switching clause between databases in T-SQL, that is not applicable here.
Try:
USE Movie; INSERT INTO Movie(title, ean) VALUES(?,?)
Note the ; IIRC, this is the same as GO in SQL proper.
You commandtext is wrong about parameterized side. Try with #title and #ean not ?,?. Like this;
cmd.CommandText = "INSERT INTO Movie(title, ean) VALUES(#title, #ean)";
Delete USE Movie part also.
Check out C# SqlParameter which is great article.
Related
I wrote this below code and I am not able to update fields.
There is no error message, however my data is not getting updated.
public void UpdateTeacher(int id, [FromBody]Teacher TeacherInfo)
{
MySqlConnection Conn = Teachers.AccessDatabase();
//Open the connection between the web server and database.
Conn.Open();
//Establish a new command(query) for our database.
MySqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "update teachers set teacherfname=TeacherFname, teacherlname=TeacherLname, employeenumber=EmployeeNumber,salary=Salary where teacherid=TeacherId";
cmd.Parameters.AddWithValue("#TeacherFname", TeacherInfo.TeacherFname);
cmd.Parameters.AddWithValue("#TeacherLname", TeacherInfo.TeacherLname);
cmd.Parameters.AddWithValue("#EmployeeNumber", TeacherInfo.EmployeeNumber);
cmd.Parameters.AddWithValue("#Salary", TeacherInfo.Salary);
cmd.Parameters.AddWithValue("#TeacherId", id);
cmd.Prepare();
cmd.ExecuteNonQuery();
Conn.Close();
}
I tried insert and delete, they are working, however update query is not working.
If you look at how you are adding your parameters, you stated that the parameter name starts with an '#' symbol.
cmd.Parameters.AddWithValue("#TeacherFname", TeacherInfo.TeacherFname);
...
But if you look at your SQL text, you have not used the '#' symbol, so you need to add this at the front of all your parameter names.
cmd.CommandText = "update teachers set teacherfname=#TeacherFname, teacherlname=#TeacherLname, employeenumber=#EmployeeNumber,salary=#Salary where teacherid=#TeacherId";
As also stated in the comments, using AddWithValue is generally considered bad. See this for more details:
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
I have created this code to add new records to the database however, every time I rum the code I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
And I have no idea how to fix this error, I have looked online and tried different ways to fix it and none of them helped or fixed the problem.
The code is found below:
SqlCommand sdk = new SqlCommand("SELECT ([Id],[Title],[JobInfo],[DateSet],[DateDue],[WhoFor]) FROM Information_Schema.Columns FROM JobInformation", ConnectToDatabase);
ConnectToDatabase.Open();
SqlDataReader reader;
reader = sdk.ExecuteReader();
ConnectToDatabase.Close();
I believe it to be the first line of code, but I have no clue where the error could be within it.
I expect you mean something like:
ConnectToDatabase.Open();
using(var sdk = new SqlCommand(
"SELECT [Id],[Title],[JobInfo],[DateSet],[DateDue],[WhoFor] FROM JobInformation",
ConnectToDatabase))
using(var reader = sdk.ExecuteReader())
{
while(reader.Read()) { /* process row */
}
ConnectToDatabase.Close();
However, you may find it easier to use a tool like dapper:
var jobs = ConnectToDatabase.Query<JobInfo>(
"SELECT [Id],[Title],[JobInfo],[DateSet],[DateDue],[WhoFor] FROM JobInformation"
).AsList();
(which does everything including the open/close, and populates the columns into your own JobInfo type that you need to create)
However, you say:
I have created this code to add new records to the database
in which case you'll need to use insert, not select - and the ExecuteNonQuery method of SqlCommand (or the Execute method of "dapper").
For an insert:
using(var cmd = new SqlCommand(#"
insert JobInformation(Title, JobInfo, DateSet, DateDue, WhoFor)
values (#title, #jobInfo, #dateSet, #dateDue, #whoFor)", ConnectToDatabase))
{
cmd.Parameters.AddWithValue("#title", title);
cmd.Parameters.AddWithValue("#jobInfo", jobInfo);
cmd.Parameters.AddWithValue("#dateSet", dateSet);
cmd.Parameters.AddWithValue("#dateDue", dateDue);
cmd.Parameters.AddWithValue("#whoFor", whoFor);
cmd.ExecuteNonQuery();
}
or with dapper:
ConnectToDatabase.Execute(#"
insert JobInformation(Title, JobInfo, DateSet, DateDue, WhoFor)
values (#title, #jobInfo, #dateSet, #dateDue, #whoFor)",
new { title, jobInfo, dateSet, dateDue, whoFor});
I'm having problems with my code. I haven't used SQL services at anytime, so its kinda tricky to figure out what's the problem. The main problem is what it says on the title, i get incorrect Syntax when i try to Read, Update or Delete data from SQL database.
Here is the code:
string Connection2 = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\AuthMyRegistery\AuthMyRegistery\Data.mdf;Integrated Security=True;User Instance=True";
string Query = "delete from * where idWorkerInfo='" + this.WorkerIdTextBox.Text + "';";
SqlConnection Conn2 = new SqlConnection(Connection2);
SqlCommand Command2 = new SqlCommand(Query, Conn2);
SqlDataReader Reader2;
Conn2.Open();
Reader2 = Command2.ExecuteReader();
MessageBox.Show("Data Deleted");
while (Reader2.Read())
{
}
Conn2.Close();
Issue is here, no table name defined
delete from * where idWorkerInfo=
Should be
Delete From TableName where idWorkerInfo=
'*' isn't a valid target for a delete statement, what table do you want to delete from?
The syntax should be something like
delete from MyTable where idWorkerInfo='abc'
You need to specify the name of table instead of a wildcard.
The basic syntax of the DELETE statement is the following (see the full documentation in MSDN - DELETE (Transact-SQL)):
DELETE FROM table_name
WHERE some_column=some_value;
Moreover, you should not be creating your SQL query using string concatenation (never ever use this in production), as this makes you vulnerable to SQL injection attacks.
Instead, you should be using a parameterized query so that all user input gets properly escaped:
var cmd = new SqlCommand("DELETE FROM MyTable WHERE idWorkerInfo=#id", conn2);
cmd.Parameters.AddWithValue("#id", WorkerIdTextBox.Text);
cmd.ExecuteNonQuery();
The query itself is incorrect.
Consider this:
delete from * where idWorkerInfo='Sth'
You need to replace * with an actual table name.
There is no * in delete ... The syntax of delete is as follows
DELETE FROM table_name
WHERE some_column = some_value;
I am accessing an Oracle database in my asp.net application, and am getting this error:
ORA-00936: missing expression
My c# code is:
getInfoByPoNum =
"SELECT h.SYS_HEADER_ID,
h.FOLIO1 AS INV_NUMBER,
v.VENDOR_NAME,
CASE WHEN h.Comments LIKE '%CLOSED%' THEN 'CLOSED' ELSE NVL(h.Comments, 'OPEN') END AS CComments,
h.ORG_ID
FROM INV_HEADERS h, VENDORS v
WHERE h.LOOKUP_CODE in ('STANDARD', 'BLANKET')
AND h.VENDOR_ID = v.VENDOR_ID
AND h.FOLIO1 = #invNumber"
OracleCommand CMD = new OracleCommand();
OracleConnection CONN = new OracleConnection(constring.ConnectionString);
CMD.Connection = CONN;
CONN.Open();
CMD.Parameters.Clear();
CMD.Parameters.Add(new OracleParameter("#invNumber", INVNumber));
CMD.CommandText = getInfoByPoNum;
using (var reader = CMD.ExecuteReader())
{
while (reader.Read())
{
The error occurs at CMD.ExecuteReader().
Based on other posts on SO and on the web, the query is correct and runs in oracle sql-developer.
What is causing the syntax error?
Update: If I modify the oracle query and enter a valid invoice number value instead of #invNumber, the query executes fine in my application.
getInfoByPoNum =
"SELECT h.SYS_HEADER_ID,
h.FOLIO1 AS INV_NUMBER,
v.VENDOR_NAME,
CASE WHEN h.Comments LIKE '%CLOSED%' THEN 'CLOSED' ELSE NVL(h.Comments, 'OPEN') END AS CComments,
h.ORG_ID
FROM INV_HEADERS h, VENDORS v
WHERE h.LOOKUP_CODE in ('STANDARD', 'BLANKET')
AND h.VENDOR_ID = v.VENDOR_ID
AND h.FOLIO1 = 2241QSA"
I believe that for Oracle your parameter should be specified as :invNumber, not #invNumber in your query:
AND h.FOLIO1 = :invNumber"
And when setting your parameter, it should look like this (just remove the #):
CMD.Parameters.Add(new OracleParameter("invNumber", INVNumber));
EDIT
You may also need to enable parameter binding by name (I think it's positional by default):
CMD.BindByName = true;
Try putting all your query in the same line, it seems that only the first line of the string is being executed. Also check if there isnĀ“t any escape character or special character that you have to treat with a "\" character.
And this may also occur, in my experience, when attempting to execute SQL with a terminating semicolon in the Oracle managed driver for .NET/C#.
So in that situation, execute the SQL within a wrapper for consistency and
do not use
SELECT * FROM X;
use
SELECT * FROM X
in other words, strip it off.
I'm new in C# programming, so I'll appreciate if anyone can help me. I know there are similar question but I still can't find the solution for my problem. I'm developing a mock system, where when user bought the product, the system will store all the transaction details. the problem is, I cannot insert the data into the database. Here's the code:
using (SqlConnection conn = new SqlConnection
(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string QueryA = "#Insert into TransDetails(AccountNumber,Amount,Provider"
+ ",Mobile Number,TransNum,TransDate, Status) "
+ " Values (#AccountNumber,#Amount,#Provider,#Mobile Number,"
+ "#TransNum,#TransDate,#Status";
using (SqlCommand cmd = new SqlCommand("InsertRecord", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = QueryA;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
}
and the stores procedures are as follows:
ALTER PROCEDURE InsertRecord1
#AccountNumber int,
#Amount nchar(10),
#Provider nchar(10),
#MobileNumber int,
#TransNum nchar(10),
#TransDate date,
#Status nchar(10)
AS
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,TransNum,TransDate,Status)
Values (#AccountNumber,#Amount,#Provider,#MobileNumber,#TransNum,#TransDate,#Status)
return
Really appreciate any help.
P/S: i dont know why the beginning of the stored procedures started with "alter".
I may be reading it wrong, but it looks like your stored procedure is not used at all. Try commenting out "cmd.CommandText = QueryA;" and substitute "cmd.CommandText = "InsertRecord1";" and change CommandType to StoredProcedure.
QueryA, by the way, is missing a paren at the end. However, the whole thing is unnecessary since you have a stored procedure that does the same thing and it's almost always preferable to use a stored procedure rather than embedded DML.
You must escape Mobile Number while brackets
Insert into TransDetails(AccountNumber,Amount,Provider,[Mobile Number],...
and remove the space in your parameter
...,#MobileNumber,#TransNum,#TransDate,#Status
and change the paramname in your command parameter
cmd.Parameters.AddWithValue("#MobileNumber", lblNumber.Text);
but seeing your stored procedure, the column Mobile Number has no space between it. Is it a typo error in your query on QueryA? If it is, then remove the space on it (also on parameter name)
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,...
or
change your CommandType.Text to CommandType.StoredProcedure and remove this line,
cmd.CommandText = QueryA;
You're using the wrong overload of the SqlCommand constructor. According to MSDN:
new SqlCommand(string, SqlConnection) Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
What you need to do is either set your CommandType for the sql command to CommandType.StoredProcedure and not use QueryA, or initialize the sql command with QueryA and not make use of your stored procedure.
As you can see there is # at the start of your SQL Statement.
Also you are not really using the Store Procedure.
You can Try this:
using (SqlConnection conn = new SqlConnection (ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("InsertRecord1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
Tho I don't use SQL Commands, Adapters...etc. to access the data from the SQL Database. I prefer Microsoft Data Access ApplicationBlocks which is easy-to-use library provided by Microsoft to access data from SQL Server.
Download
You can download it here http://download.microsoft.com/download/VisualStudioNET/daabref/RTM/NT5/EN-US/DataAccessApplicationBlock.msi
Introduction
https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx