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});
Related
I am currently trying to make a prepared command, but for some reason am I getting this error
Hint "There is a column named \"entity_id\" in table \"temp_country\", but it cannot be referenced from this part of the query." string
when I do this
connection.Execute(#$"DROP TABLE IF EXISTS temp_{entityName}; select * into temp_{entityName} from {entityName}");
var getNewIdSql =
$"INSERT INTO \"temp_{entityName}\"(entity_id) values(#entity_id) RETURNING entity_id";
NpgsqlCommand insertEntry = new NpgsqlCommand(getNewIdSql, connection, transaction);
insertEntry.Prepare();
and I am ont sure what I am doing wrong here? because table exist, and has the column? so I am not sure why this is going wrong.
The error message is indeed misleading, but the problem is simply that you haven't added an NpgsqlParameter for entity_id to the NpgsqlCommand before calling Prepare:
NpgsqlCommand insertEntry = new NpgsqlCommand(getNewIdSql, connection);
var param = new NpgsqlParameter("entity_id", NpgsqlDbType.Integer);
insertEntry.Parameters.Add(param);
insertEntry.Prepare();
I'm using MySQL to try and add a new user to my database. User got an Id, a First Name, a Last Name and a Date of Birth. But when I run the code below (And run conn.close() after I'm done) the database tells me (using HeidiSQL) that in the Table Overview there is now a new row in the table but when I open the Data Tab to look at the rows, there is nothing. It's empty. Running a COUNT(*) also returns 0.
using (MySqlTransaction transaction = conn.BeginTransaction())
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO USERS(NAME_FIRST,NAME_LAST,DATE_OF_BIRTH) VALUES(#nameFirst,#nameLast,#dateOfBirth)";
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#nameFirst", user.NameFirst);
cmd.Parameters.AddWithValue("#nameLast", user.NameLast);
cmd.Parameters.AddWithValue("#dateOfBirth", user.DateOfBirth);
cmd.Prepare();
cmd.ExecuteNonQuery();
lastInsertId = (uint)cmd.LastInsertedId;
}
}
I get no errors. Nothing shows up in any log and everyone sees the same as me.
What am I doing wrong?
It feels like it's the use of begintransaction which starts a transaction. This means autocommit=false for the entirety of the transaction.
After ExecuteNonQuery Do a transaction.Commit(); and see if they show up.
More Info Here
Hey all I am using the following query in my C# program:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlDevConnection"].ConnectionString);
SqlCommand command = new SqlCommand(Q, con);
con.Open();
command.Parameters.AddWithValue("#val0", buildTblVal.ToString());
command.Parameters.AddWithValue("#val1", recordID);
command.ExecuteNonQuery();
command.Dispose();
con.Close();
Seems I am getting an error of Additional information: Incorrect syntax near the keyword 'WHERE'. when it gets to the command.ExecuteNonQuery();.
The query looks like this:
UPDATE
[tTrip]
SET
#val0
WHERE
RequestID = #val1
And when its populated it looks like this:
UPDATE
tT
SET
RequestType=75,
TripLead='Barker, Bob',
Category=2,
RequestDate='2016-12-15',
ApproxDate='2016-12-15',
AtC='yes',
TStatus='New',
LastModifiedBy='bob\barker',
LastModifiedDate='2017-04-18 10:24 AM'
WHERE
RequestID = 779
I get the error of:
Additional information: Incorrect syntax near the keyword 'WHERE'.
However, when I copy that same query and paste it into SSMS it runs just fine.
What would I be missing?
Parameters are value placeholders, they cannot be sql clauses, statements, etc. That is why it fails because you cannot pass in a whole string for the SET clause as a parameter.
For example, this is how parameters should be used.
UPDATE
tT
SET
RequestType = #requestType,
TripLead = #tripLead,
Category = #category
-- etc
WHERE
RequestID = #requestID
On a side note it is considered best practice to wrap your instances in using blocks where the type implements IDisposable. This ensures that resources are always freed even in the event of an Exception. When working with databases this is a must as it guarantees that connections are not left open until garbage disposal runs (which is non-deterministic).
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlDevConnection"].ConnectionString))
using(SqlCommand command = new SqlCommand(Q, con))
{
con.Open();
// add parameters correctly based on above example
command.Parameters.AddWithValue("#val1", recordID);
command.ExecuteNonQuery();
}
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.
I would like to know how can I get record count of a query with C#.
Here is the code that I use..
MySqlDataReader recordset = null;
query = new MySqlCommand("SELECT * FROM test ORDER BY type_ID ASC", this.conn);
recordset = query.ExecuteReader();
while (recordset.Read())
{
result.Add(recordset["type_ID"].ToString());
}
return result;
I was using a SELECT COUNT(*) and expected an int to be returned. You may need this to get a usable value:
mysqlint = int.Parse(query.ExecuteScalar().ToString());
A couple of things...
The SQL statement you would use is:
SELECT COUNT(*) FROM test
However, when using the MySQL Connector/Net to connect to MySQL through C# there is some care to be given when handling query results.
For example, as cited in this question and on Microsoft Connect int.Parse("0") equivalently known as Int32.Parse("0") can throw a FormatException on some machines.
I have found that Convert.ToInt32 handles this case nicely.
So your code will be something like this:
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand("SELECT COUNT(*) FROM test", conn))
{
int count = Convert.ToInt32(cmd.ExecuteScalar());
return count;
}
}
Remember to make use of using statements in order to ensure that the MySQL objects get disposed of properly.
You're adding a new element in result for each row. Depending on the type of result you should be able to do something like result.Count after the while loop completes.
You could run another query first to get the count :
query = new MySqlCommand("SELECT count(*) as theCount FROM test ORDER BY type_ID ASC", this.conn);
but in truth, you are probably best changing the problem so you wont need the count until after you have populated the list.