Decrement value by 1 MS Access SQL and C# [duplicate] - c#

This question already has answers here:
How can I add user-supplied input to an SQL statement?
(2 answers)
Closed 4 years ago.
I'm facing a problem with decrementing value with MS Access database.
I get an error
Syntax error in UPDATE Statement
My code:
connection.Open();
command = new OleDbCommand();
command.Connection = connection;
command.CommandText = " update Cards set Count = Count - 1 where Type=" + ct + " ";
command.ExecuteNonQuery();
connection.Close();
Can anyone please help?

You should provide an actual error.
My guess is that count is a keyword and has to be put in square brackets like so [count]
and do use parameters, see Joel's answer

It's not certain, but I strongly suspect it's missing single quotes around ct. Fix it like this:
using (var connection = new OleDbConnection("connection string here"))
using (var command = new OleDbCommand("update Cards set Count = Count - 1 where Type= ?", connection))
{
//have to guess at the OleDbType value. Use the actual column type and length from the database
cmd.Parameters.Add("?", OleDbType.VarWChar, 10).Value = ct;
connection.Open();
command.ExecuteNonQuery();
}
There are several other important fixes in this pattern, too.

Related

Upload CSV File In C# [duplicate]

This question already has an answer here:
ORA-00936 missing expression
(1 answer)
Closed 3 years ago.
I have got problem when I try to upload my csv file into Oracle Database in C#. The error message occured like this {"ORA-00936: missing expression"}. I have no idea to fix it. Does anyone here could help me to solve this problem please.
This is my current code;
conn.Open();
foreach(DataRow importRow in importData.Rows)
{
OracleCommand cmd = new OracleCommand("INSERT INTO TMCI_PPC_IMPORTDATA_PSI (ITEM, REQUIREMENT, REQ_DATE)" +
"VALUES (#Itm, #Req, #ReqDT)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Itm", importRow["ITEM"]);
cmd.Parameters.Add("#Req", importRow["REQUIREMENT"]);
cmd.Parameters.Add("#ReqDT", importRow["REQ_DATE"]);
cmd.ExecuteNonQuery();
}
Several issues:
Oracle uses :, not # for parameters
You should create parameters once, before loop.
Code:
...
conn.Open();
// Oracle uses : not # for parameters
string query =
#"INSERT INTO TMCI_PPC_IMPORTDATA_PSI (
ITEM,
REQUIREMENT,
REQ_DATE)
VALUES (
:Itm,
:Req,
:ReqDT)";
//DONE: wrap IDisposable into using
using (OracleCommand cmd = new OracleCommand(query, conn)) {
//DONE: create parameters once
//TODO: validate parameters' types
cmd.Parameters.Add(":Itm", OracleDbType.Varchar2);
cmd.Parameters.Add(":Req", OracleDbType.Varchar2);
cmd.Parameters.Add(":ReqDT", OracleDbType.Date);
foreach(DataRow importRow in importData.Rows) {
// assign parameters as many as you want
cmd.Parameters[":Itm"].Value = importRow["ITEM"];
cmd.Parameters[":Req"].Value = importRow["REQUIREMENT"];
cmd.Parameters[":ReqDT"].Value = importRow["REQUIREMENT"];
cmd.ExecuteNonQuery();
}
}
I am pretty sure the parameters need to have : as a prefix not #
OracleCommand cmd = new OracleCommand("INSERT INTO TMCI_PPC_IMPORTDATA_PSI (ITEM, REQUIREMENT, REQ_DATE)" +
"VALUES (:Itm, :Req, :ReqDT)", conn);
And change your paramters to be like the following:
command.Parameters.Add(new OracleParameter("Itm", importRow["ITEM"]);

Problems inserting into Access Database on dependent tables [duplicate]

This question already has answers here:
OleDbCommand parameters order and priority
(3 answers)
Is order of parameters for database Command object really important?
(3 answers)
OleDbParameters and Parameter Names
(2 answers)
Closed 4 years ago.
I have an access database with my work that I am trying to insert into but I keep getting.
'You cannot add or change a record because a related record is required in table 'Projects'.'
I'm running this query: INSERT INTO Tasks (Assigned,Project,Description) VALUES (#assign,#project,#description)
On this Structure: picture of database structure in access
With this code in C# with an OleDb... commands and connections Which are working fine for other query's:
private void addTaskBTN_Click(object sender, EventArgs e)
{
//the assign id is already known and is of type integer.
string query = "SELECT Project_ID FROM Projects WHERE Project_Name = #project";
OleDbConnection con = new OleDbConnection(con_string);
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#project", projectComboBox.Text);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
project_id = Convert.ToInt16(reader[0]);
Console.WriteLine(project_id);
}
con.Close();
Console.WriteLine("submit: " + project_id + " " + employee_id + " " + descriptionTextBox.Text + " " + monthCalendar1.SelectionStart);
Console.WriteLine(monthCalendar1.SelectionStart);
query = "INSERT INTO Tasks (Assigned,Project,Description) VALUES (#assign,#project,#description)";
con = new OleDbConnection(con_string);
cmd = new OleDbCommand(query, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#project", project_id);
cmd.Parameters.AddWithValue("#assign", employee_id);
cmd.Parameters.AddWithValue("#description", descriptionTextBox.Text.ToString());
//cmd.Parameters.AddWithValue("#deadline", monthCalendar1.SelectionStart);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
this.Close();
}
I have tried looking at other examples of this problem and I don't understand why I'm getting this error. #project has a valid id number of the primary key for a Project, #assign has a valid employee id as well and #description is string of text. Thanks for any help.
Steve correctly identified the mistake you have to put your parameters in the right order. My fix was to arrange my parameters in order.

ExecuteScalar has not been initialized [duplicate]

This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 7 years ago.
I keep getting this error saying that "ExecuteScalar has not been initialized" I have new to C# but had a look through google and tutorials and still cant see what the problem is. Its probably a very silly mistake but if anyone could help. Thanks :)
// open connection
myConnection.Open();
// sql command
string Account_Num = txt_acc.Text;
string Pin_num = txt_pin.Text;
SqlCommand check_details = new SqlCommand("select Account_num, Pin_num from Cust_details where Account_num='" + txt_acc.Text + "'and Pin_num ='" + txt_pin.Text + "'");
check_details.Parameters.AddWithValue("#Account_num", txt_acc.Text);
check_details.Parameters.AddWithValue("#Pin_num", txt_pin.Text);
int result = Convert.ToInt32(check_details.ExecuteScalar());
if (result > 0)
{
Console.WriteLine("user exists");
}
else
{
Console.WriteLine("error");
}
}
Looks like you didn't connect your command with connection. Just set it's Connection property to myConnection.
check_details.Connection = myConnection;
or you can set it on your SqlCommand constructor as a second parameter;
SqlCommand check_details = new SqlCommand("yourCommand", myConnection);
or you can use CreateCommand method from your connection;
SqlCommand check_details = myConnection.CreateCommand();
And you are misunderstood the parameterized queries. You still do string concatenation in your sql query but you try to add parameters. That's meaningless.
Use using statement to dispose your connection and command automatically as well.
Also don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type and it's size.
using(var myConnection = new SqlConnection(conString))
using(var check_details = myConnection.CreateCommand())
{
check_details.CommandText = #"select Account_num, Pin_num from Cust_details
where Account_num = #accnum
and Pin_num = #pinnum";
// I assume your column types as Int
check_details.Parameters.Add("#accnum", SqlDbType.Int).Value = int.Parse(txt_acc.Tex);
check_details.Parameters.Add("#pinnum", SqlDbType.Int).Value = int.Parse(txt_pin.Text);
myConnection.Open();
int result = (int)check_details.ExecuteScalar();
...
}
By the way, there is no point to select Pin_num column in your command since ExecuteScalar ignores it.

ERROR : The multi-part identifier could not be bound, c# console Application

SqlConnection cn = new SqlConnection("user id=ID;" +
"password=PASS;server=svr;" +
"Trusted_Connection=no;" +
"database=db; " +
"connection timeout=30");
cn.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = cn;
Console.WriteLine(ListofOrders.Count);
for (int i = 0; i < ListofOrders.Count; i++)
command1.CommandText += string.Format("update table set Status='Expired' where GUID={0};", ListofOrders[i].ToString());
command1.ExecuteNonQuery();
// LogicHandler.UpdateActiveOrders();
Console.WriteLine("DONE", ConsoleColor.Cyan);
Getting error at this step: command1.ExecuteNonQuery(); Error Message: The multi-part identifier could not be bound.
What i am trying here is I am running a select query and getting that data into the ListofOrders list from that I wanna run the update to those data in the list.
Please help
If you use a Reserved Keyword like table you have to wrap it in square brackets: [table]. But it would be better to not use them in the first place.
I guess you need to wrap the Guid with apostrophes like in GUID='{0}'. Howver, you should use sql-parameters instead of string concatenation, always. That prevents also sql-injection.
string update = #"update tablename -- or [Table] but i wouldnt do that
set Status='Expired'
where GUID=#GUID";
command1.CommandText = update;
command1.Parameters.Add("#GUID", SqlDbType.UniqueIdentifier).Value = new Guid(ListofOrders[i].ToString());
As an aside, why have you used command1.CommandText += instead of just command1.CommandText =? That is at least confusing, if you reuse the command it could also cause errors.

C# 'select count' sql command incorrectly returns zero rows from sql server

I'm trying to return the rowcount from a SQL Server table. Multiple sources on the 'net show the below as being a workable method, but it continues to return '0 rows'. When I use that query in management studio, it works fine and returns the rowcount correctly. I've tried it just with the simple table name as well as the fully qualified one that management studio tends to like.
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = sqlConnectionString;
cn.Open();
SqlCommand commandRowCount = new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn);
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count: " + countStart.ToString());
}
Any suggestions on what could be causing it?
Here's how I'd write it:
using (SqlConnection cn = new SqlConnection(sqlConnectionString))
{
cn.Open();
using (SqlCommand commandRowCount
= new SqlCommand("SELECT COUNT(*) FROM [LBSExplorer].[dbo].[myTable]", cn))
{
commandRowCount.CommandType = CommandType.Text;
var countStart = (Int32)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count: " + countStart.ToString());
}
}
Set your CommandType to Text
command.CommandType = CommandType.Text
More Details from Damien_The_Unbeliever comment, regarding whether or not .NET defaults SqlCommandTypes to type Text.
If you pull apart the getter for CommandType on SqlCommand, you'll find that there's weird special casing going on, whereby if the value is currently 0, it lies and says that it's Text/1 instead (similarly, from a component/design perspective, the default value is listed as 1). But the actual internal value is left as 0.
You can use this better query:
SELECT OBJECT_NAME(OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
WHERE index_id < 2 AND OBJECT_NAME(OBJECT_ID)=N'YOUR_TABLE_NAME'

Categories