Related
Im trying to insert this test data in my sql database and I'm getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'
Any ideas how to solve this?
DateTime date = DateTime.Now;
string test = "{'payload': {'businessName': 'COMPANY1', 'subscriberName': 'JOHN DOE', 'accountNumber': 'CY68005000121234567890123456', 'numberOfRecords': 1," +
"'currentBalance': 4195.5, 'transactions': [{'transactionNumber': 'TR00000000','sequenceNumber': '000','transactionCode': '305','actualDateTime': '201812041624'," +
"'transactionValueDate': '2018-12-04', 'transactionCurrencyCode': 'EUR', 'transactionAmount': -1149.5, 'balance': 4195.5, 'chequeNo': '', 'depositedBy': 'CY68005000121234567890123456'," +
"'customerReference': 'uniqueValue', 'paymentNotes': 'NOTES', 'exchangeRate': 0}]}, 'errors': null}";
trans = JsonConvert.DeserializeObject<HB_transactions>(test);
for (int i=0; i<trans.payload.transactions.Count; i++)
{
string query = "SELECT TransactionId FROM AABankTransTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dataReader = cmd.ExecuteReader();
bool exists = false;
while(dataReader.Read())
{
if(dataReader[0].ToString() == trans.payload.transactions[i].transactionNumber)
{
exists = true;
break;
}
}
dataReader.Close();
if (exists) continue;
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES ('" + trans.payload.transactions[i].transactionNumber + "', 'HB', " + args[0] + ", '" + trans.payload.transactions[i].transactionCurrencyCode + "', " +
trans.payload.transactions[i].transactionAmount + ", " + date + ", 0, '" + trans.payload.transactions[i].depositedBy + "', '" +
trans.payload.transactions[i].paymentNotes + "', " + DateTime.Parse(trans.payload.transactions[i].transactionValueDate) + ")";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
Solved by using SQL parameters instead of string concatenation.
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES (#TransID, 'HB', #COMID, #curr, #amount, #dlDate, 0, #depositor, #Details, #TransDate)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#TransID", trans.payload.transactions[i].transactionNumber);
cmd.Parameters.AddWithValue("#COMID", args[0]);
cmd.Parameters.AddWithValue("#curr", trans.payload.transactions[i].transactionCurrencyCode);
cmd.Parameters.AddWithValue("#amount", trans.payload.transactions[i].transactionAmount);
cmd.Parameters.AddWithValue("#dlDate", date);
cmd.Parameters.AddWithValue("#depositor", trans.payload.transactions[i].depositedBy);
cmd.Parameters.AddWithValue("#Details", trans.payload.transactions[i].paymentNotes);
cmd.Parameters.AddWithValue("#TransDate", DateTime.Parse(trans.payload.transactions[i].transactionValueDate));
cmd.ExecuteNonQuery();
I am trying to add a record to my database using the following function
The Error occurs at
adapter.InsertCommand.ExecuteNonQuery();
Full code:
public void Insert()
{
string query;
myDB.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(#"SELECT * From Eiendom", myDB);
query = #"INSERT INTO Eiendom (AreaID, AgentID, KlientID, AdresID, EiedomAantalBadkamers, EiedomAantalSlaapkamers, EiendomPrys, EiedomSwembad, EiedomGarages, EiedomAantalVloere, EiedomOppervlakte, EiedomTipePlan, EiedomAdisioneleInligting)
VALUES ('" + areaID + " , " + agentID + " , " + klientID + " , "
+ adressID + " , " + badkamers + " , " + slaapkamers + " , " + prys + " . "
+ " , " + swembad + " , " + garages + " , " + vloere + " , " + oppervlakte
+ " , " + plan + " , " + inligting + "')" ;
OleDbCommand insert = new OleDbCommand(query, myDB);
adapter.InsertCommand = insert;
adapter.InsertCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Eiendom");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Eiendom";
myDB.Close();
}
I get an error that says ;
System.Data.OleDb.OleDbException: 'Number of query values and destination fields are not the same.'
I actually do understand as to why this is presenting itself as I am not adding the autonumber column I have in my database
So what I'm asking is what can I do as a workaround to add the record but the auto number column fills itself in when adding the record?
You don't need to hand craft your InsertCommamd. The OleDbCommandBuilder can do it all for you. I think it should deal with Autonumbers.
var cbr = new OleDbCommandBuilder(adapter);
cbr.QuotePrefix = "[";
cbr.QuoteSuffix = "]";
adapter.InsertCommand = cbr.GetInsertCommand(true);
I've been looking for its solution for some time now, I've seen similar questions here on SO but the answers there didn't solve my problem. In my situation, I would like to loop through the rows of datagridview values to insert it to MySql database. The number of rows in the datagridview will depend on the user. When I try to input 2 or more rows of datagridview values and try to insert it to the database, only the first row of data is inserted successfully.
Here is my code:
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
The error: Parameter '#num_Delivery' has already been defined. I'm new at using C# language. Any ideas and suggestions would be welcomed.
You can do it like this. It should work.
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
cmd.Parameter.Clear();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
Move
MySqlCommand cmd = new MySqlCommand();
in the for loop:
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
or clear its Parameters collection:
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
Sql string can be out of loop.
After approximately 40 seconds of running this code and inserting ~400 records into the table I get a
OleDbException was Unhandled - Unspecified Error.
A copy of the code:
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
string sqlStr;
dbConnector.Connect();
sqlStr = " SELECT MAX(EventID) AS MaxID" +
" FROM Events";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
EventID = Convert.ToInt16( dr[0].ToString());
}
dr.Close();
sqlStr = " SELECT MemberID" +
" FROM GroupMembers" +
" WHERE (GroupID = " + GroupID + ")";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
MemberID = Convert.ToInt16( dr[0].ToString());
clsDBConnector dbConnectorInsert = new clsDBConnector();
string cmdStr = "INSERT INTO EventsAtendees " +
"(MemberID, EventID) " +
"VALUES (" + MemberID + ", " + EventID + ")";
dbConnectorInsert.Connect();
dbConnectorInsert.DoDML(cmdStr);
dbConnectorInsert.close();
}
dr.Close();
I have taken out the custom fields and variables to make this more useable by everyone.
I am using these lines of code to check if the record exists or not.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
But I am getting an error:
Object reference not set to an instance of an object.
I want to do:
if (UserExist > 0)
// Update record
else
// Insert record
ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method.
From MSDN;
Return Value
The first column of the first row in the result set, or a null
reference if the result set is empty.
You might need to use COUNT in your statement instead which returns the number of rows affected...
Using parameterized queries is always a good practise. It prevents SQL Injection attacks.
And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also.
As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand:
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}
The ExecuteScalar method should be used when you are really sure your query returns only one value like below:
SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
If you want the whole row then the below code should more appropriate.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
//User Exists
}
else
{
//User NOT Exists
}
sqlConnection.Open();
using (var sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "'", sqlConnection))
{
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
lblMessage.Text ="Record Already Exists.";
}
else
{
lblMessage.Text ="Record Not Exists.";
}
reader.Close();
reader.Dispose();
}
sqlConnection.Close();
MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
// Exist
}
else {
// Add
}
I would use the "count" for having always an integer as a result
SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist == 1) //anything different from 1 should be wrong
{
//Username Exist
}
try this
public static bool CheckUserData(string phone, string config)
{
string sql = #"SELECT * FROM AspNetUsers WHERE PhoneNumber = #PhoneNumber";
using (SqlConnection conn = new SqlConnection(config)
)
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#PhoneNumber", phone);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
return true; // data exist
}
else
{
return false; //data not exist
}
}
}
}
Use try catch:
try
{
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
// Update query
}
catch
{
// Insert query
}
You can write as follows:
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
//Username Exist
}
}
I was asking myself the same question, and I found no clear answers, so I created a simple test.
I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository.
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault()
If e Is Nothing Then
employees.Insert(newE)
End If
Next
2.1 seconds
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Try
employees.Insert(newE)
Catch ex As Exception
End Try
Next
3.1 seconds
sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM tblAttendance",con);
sda.Fill(dt);
string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);
if (bar >= 1){
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "empty");
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
string s = #"SELECT * FROM tbl1 WHERE CodNo = #CodNo";
SqlCommand cmd1 = new SqlCommand(s, con);
cmd1.Parameters.AddWithValue("#CodNo", txtid.Text);
con.Open();
int records = (int)cmd1.ExecuteScalar();
if (records > 0)
{
Response.Write("<script>alert('Record not Exist')</script>");
}
else
{
Response.Write("<script>alert('Record Exist')</script>");
}
}
private void insert_data()
{
SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(#CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',#image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',#NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);
flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
string img = #"~/File/" + flpimage.FileName;
flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
string img1 = #"~/Tazkiera/" + flpnidcard.FileName;
comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
comm.Parameters.AddWithValue("image", flpimage.FileName);
comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);
comm.ExecuteNonQuery();
con.Close();
Response.Redirect("~/SecondPage.aspx");
//Response.Write("<script>alert('Record Inserted')</script>");
}
}
Use the method Int.Parse() instead. It will work.
I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.
var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
if (result == null) {
register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
} else {
MessageBox.Show("User Alreay Exist. Try with Different Username");
}