I am using an OleBdCommand To Insert A record into a Db, but the update never persists.
Here is the Code
public void InsertCandidate(XElement element, ref OleDbDataAdapter adapter, OleDbConnection sqlConnStr)
{
if (sqlConnStr.State == ConnectionState.Broken || sqlConnStr.State == ConnectionState.Closed)
sqlConnStr.Open();
try
{
string query = "Insert Into Candidate Values(#priKey, #Name, #LName, #Phone, #Add)";
OleDbCommand InsertCandidate = new OleDbCommand(query, sqlConnStr);
InsertCandidate.Parameters.AddWithValue("priKey", element.Attribute("CAND_NUM").Value);
InsertCandidate.Parameters.AddWithValue("Name", element.Attribute("CAND_FNAME").Value);
InsertCandidate.Parameters.AddWithValue("LName", element.Attribute("CAND_LNAME").Value);
InsertCandidate.Parameters.AddWithValue("Phone", element.Attribute("CAND_PHONE").Value);
InsertCandidate.Parameters.AddWithValue("Add", element.Attribute("CAND_ADDRESS").Value);
InsertCandidate.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + ex.Message);
}
}
NO exceptions, errors or anomalies are generated!
Any Advice
M
I even tried this.
//InsertCandidate.ExecuteNonQuery();
adapter.InsertCommand = InsertCandidate;
adapter.InsertCommand.ExecuteNonQuery();
*Thanks Every One *
Aiden's Code Worked, but i should have read Tony's Post Better hence i accepted his answer (he said it first)
Kind Regards
And Thanks Once Again!
Have you executed your SQL statement in isolation from your code to make sure it works?
As you have not posted the table definition it could be because you are not specifying the fields in your insert statement.
I'm not an OLEDB expert but all the examples I can find on the net use question marks in place of parameters. Try the SQL statement like this:
string query = "Insert Into Candidate Values(?, ?, ?, ?, ?)";
Update
Looking at the documentation for the OleDBCommand it will only throw an InvalidOperationException and not an OleDbException in the event of an error. You should add this exception handler and see if that gives you any more information.
Alternatively change your exception hanndler to catch the generic Exception type to see if you even get an exception.
string query = "Insert Into Candidate Values(?, ?, ?, ?, ?)";
OleDbCommand InsertCandidate = new OleDbCommand(query, sqlConnStr);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_NUM").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_FNAME").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_LNAME").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_PHONE").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_ADDRESS").Value);
//InsertCandidate.ExecuteNonQuery();
adapter.InsertCommand = InsertCandidate;
adapter.InsertCommand.ExecuteNonQuery();
this will work!
Related
I am currently trying to implement SQL into a project with Unity3D. So far, I was able to do "normal" UPDATE, ADD, DELETE, DROP, ALTER, INSERT".
Trying to go a step further, I am trying to insert prepared statements, using this link as a guide
Here is my code :
SqlConnection sqlConnection = new SqlConnection(Connection.connectionString)
sqlConnection.Open();
SqlCommand cmd = new SqlCommand(null, sqlConnection);
cmd.CommandText = "INSERT INTO IngredientTypes (Name) VALUES (#name)";
SqlParameter nameParam = new SqlParameter("#name", SqlDbType.Text, 155);
nameParam.Value = Name;
cmd.Parameters.Add(nameParam);
cmd.Prepare();
cmd.ExecuteNonQuery();
My table looks like so :
CREATE TABLE IngredientTypes
(
IngredientTypeID INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(155)
);
I get this error :
SQLException : Incorrect systax near '1'.
System.Data.SqlClient.SqlConnection.ErrorHandler (System.Object sender, Mono.Data.Tds. Protocol.TdsInternalErrorMessageEventArgs e)
Help please? Thank you in advance.. I can't find where I did wrong.
You can reduce that code quite a bit with no loss of function, and even some important improvements (for example, this will close the connection even if an exception is thrown):
using (var sqlConnection = new SqlConnection(Connection.connectionString))
using (var cmd = new SqlCommand("INSERT INTO IngredientTypes (Name) VALUES (#name)", sqlConnection))
{
cmd.Parameters.Add("#name", SqlDbType.VarChar, 155).Value = Name;
sqlConnection.Open();
cmd.ExecuteNonQuery();
}
I'm not sure what's causing that exception in your existing code, though, because 1 is not used anywhere in that query. I suspect the problem has something to do with SqlDbType.Text, since that is not the correct type to use with a VarChar column, but it seems just as likely there's code somewhere we haven't seen yet that's changing your SQL command text.
Definitely the Prepare() method in your link is not needed for Sql Server. It's inherited here from DbCommand, where it's included because it's an important part of the API for some other databases, but Sql Server has handled this automatically for more than 10 years now.
SqlDbType.Text Is not the same as varchar. I don’t believe Text types have a length you specify.
Could you try below? Using the "using" structure is safer for sql connections by the way, the connection automatically closes when your process is done.
using (SqlConnection sqlConnection = new SqlConnection(Connection.connectionString))
{
SqlCommand command = new SqlCommand("INSERT INTO IngredientTypes (Name) VALUES (#name)", connection);
command.Parameters.Add("#name", SqlDbType.Varchar, 155);
command.Parameters["#name"].Value = Name; //make sure Name is string.
try
{
sqlConnection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I tried your code exactly as it is and found no issue. Though there are few compilation errors (missing ; in line 1 and Name variable should be coming as parameter) but I am sure you know that. If you have posted your table structure and code exactly the same as you have in your project, then there is no problem in this code.
I need your assistance. I have created form and insert some data into SQL Server. But I always get an error. I think I made a mistake when creating the SQL Server connection.
code is below
OleDbConnection con = new OleDbConnection("Provider=sqloledb;SERVER=NEVZAT-PC;DATABASE=DENEME;User ID=11;password=1111;");
OleDbCommand cmd = new OleDbCommand("insert into isemri (isemrino,isyeri,isalani,isemridet,bastar,bittar)values(#isemrino,#isyeri,#isalani,#isemridet,#bastar,#bittar)", con);
cmd.Parameters.AddWithValue("#isemrino", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#isyeri", comboBox1.Text);
cmd.Parameters.AddWithValue("#isalani", comboBox2.Text);
cmd.Parameters.AddWithValue("#isemridet", richTextBox1.Text);
cmd.Parameters.AddWithValue("#bastar", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#bittar", dateTimePicker2.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
and I get this error:
enter image description here
From what it seems to me the issue is that you're using undeclared variables in your query, you have to either declare the variables before insert, or use other methodes that don't use variables.
You are receiving "Must declare the scalar variable" error.
OleDb does not support named parameters. I presume this is what is
causing the errors. Instead, within the SQL query, use ? instead of
the param name, and ensure the order of parameters added matches the
order they appear in the query.
Apply ? sign in insert query
Tried with using statement
[Optional step : ] Applied all parameter, also used DBNull.Value in case of the table field is nullable
Please check below code:
OleDbConnection con = new OleDbConnection("Provider=sqloledb;SERVER=NEVZAT-PC;DATABASE=DENEME;User ID=11;password=1111;");
using(OleDbCommand cmd = new OleDbCommand("insert into isemri (isemrino,isyeri,isalani,isemridet,bastar,bittar) values (?, ?, ?, ?, ?, ?)", conn))
{
cmd.Parameters.AddWithValue("#isemrino", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#isyeri", comboBox1.Text ?? DBNull.Value);
cmd.Parameters.AddWithValue("#isalani", comboBox2.Text ?? DBNull.Value);
cmd.Parameters.AddWithValue("#isemridet", richTextBox1.Text ?? DBNull.Value);
cmd.Parameters.AddWithValue("#bastar", dateTimePicker1.Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("#bittar", dateTimePicker2.Value ?? DBNull.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The INSERT INTO statement contains the following unknown field name:
'NoName'. Make sure you have typed the name correctly, and try the
operation again.
That is the error thrown when I try to insert a record into a dbase file (.dbf) from a .Net app I am working on.
I use Oledb connection like this:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\David\Desktop\Dbase_Files;Extended Properties=dBASE IV;User ID=Admin;Password=");
I had similar issues while selecting. Some columns get returned as 'NoName' but still with data. I simply use the column index number in place of the column name.
Now I need to insert and it has been a block. Same error comes up with say (when you don't list out the column names):
INSERT INTO [tablename.dbf] VALUES (?, ?, ?);
Sample full code below:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\David\Desktop\Dbase_Files;Extended Properties=dBASE IV;User ID=Admin;Password=");
connection.Open();
OleDbTransaction trans = connection.BeginTransaction();
OleDbCommand command = new OleDbCommand(#"INSERT INTO [tablename.DBF]
VALUES
(
?, ?, ?
);", connection, trans);
command.Parameters.AddWithValue("param1", 7);
command.Parameters.AddWithValue("param2", "RCN");
command.Parameters.AddWithValue("param3", 0);
try
{
command.ExecuteNonQuery();
trans.Commit();
}
catch (Exception e)
{
trans.Rollback();
throw e;
}
finally
{
connection.Close();
}
I have seen forums discuss this when it happens in Ms Access. But nothing much so far on dbase. Been thinking it is a driver thing.
The dbase file was created by dbase plus (2007) application.
Don't use question marks in combination with named parameters, even #param1 etc. If you're inserting three values into this table, then name the parameters in the command text:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\David\Desktop\Dbase_Files;Extended Properties=dBASE IV;User ID=Admin;Password=");
connection.Open();
OleDbTransaction trans = connection.BeginTransaction();
OleDbCommand command = new OleDbCommand(#"INSERT INTO [tablename.DBF]
VALUES
(
#param1, #param2, #param3
);", connection, trans);
command.Parameters.AddWithValue("param1", 7);
command.Parameters.AddWithValue("param2", "RCN");
command.Parameters.AddWithValue("param3", 0);
try
{
command.ExecuteNonQuery();
trans.Commit();
}
catch (Exception e)
{
trans.Rollback();
throw e;
}
finally
{
connection.Close();
}
You are very close, but what you are probably failing on is the telling of WHICH columns you are inserting the values. Yes, OleDB uses "?" as place-holders for the parameters and they must match the same order as their corresponding needs of the SQL select, insert, update or delete. Add the explicit columns BEFORE the "Values" clause.
OleDbCommand command = new OleDbCommand(
#"INSERT INTO [tablename.DBF] ( tblColumn1, tblColumn2, tblColumn3 )
VALUES ( ?, ?, ? )", connection, trans);
THEN add your parameters in the specific order to match the command.
No need for the closing semi within the command statement as you only had one insert command anyhow.
The actual naming of the parameters as you had was ok for your own clarification, but the order of parameters is specifically correlated to the "?" place-holders in the insert statement.
I found out after a long time that this happened to tables with field-name longer than 8 or 9 characters. When its 10 or more characters long, the field name returns 'NoName'.
It sounds ridiculous.
When I made the field-name shorter this worked fine.
I got some insight into this here
Now with the fieldnames adjusted, my sample code above works perfectly.
I'm developing the username/password creation system for my program. It's just going to be used in a computing lab, and I'm just going to have a central Access database that distributes through scripts on the lab machines. Or that's the plan right now. I can't remember the proper code to insert the info into the database to save my life though. This is what I've got so far. The hashing and salting seem to be going fine, I just can't shove it into the database. The name of the table is regulate.
I'm getting "number of query fields and destination fields are not the same".
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=access.mdb";
conn.Open();
string Name = txtName.Text;
string PW = txtHash.Text;
string Salt = txtSalt.Text;
OleDbCommand cmmd = new OleDbCommand("INSERT INTO regulate(regulate) Values(#NAME, #PASSWORD, #SALT)", conn);
if (conn.State == ConnectionState.Open)
{
cmmd.Parameters.Add("#NAME", OleDbType.VarWChar, 100).Value = Name;
cmmd.Parameters.Add("#PASSWORD", OleDbType.VarWChar, 500).Value = PW;
cmmd.Parameters.Add("#SALT", OleDbType.VarWChar, 10).Value = Salt;
try
{
cmmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
conn.Close();
}
catch (OleDbException expe)
{
MessageBox.Show(expe.Message);
conn.Close();
The OleDbCommand uses a different format for parameters than SqlCommand, as you see in the documentation:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
And as #codenheim suggests, check the syntax of your INSERT command.
Also, PASSWORD is a reserved word in Jet SQL, so you probably need to quote that column name. I believe either these quote styles would work:
INSERT INTO regulate(name, `password`, salt) Values(?, ?, ?)
INSERT INTO regulate(name, [password], salt) Values(?, ?, ?)
The number of fields and types in this:
INSERT INTO regulate(regulate)
must match this:
Values(var1, var2, var3)
Should be something like:
INSERT INTO regulate(name, password, salt) Values(?, ?, ?)
assuming these are the column names.
PS: I don't use OleDb very often, but I believe you need ? instead of named #arg per #p.s.w.g's answer. (Upvote his/her answer if this helps). I can confirm all of my OleDb code does indeed use positional arguments only.
First important thing is to make sure that your path to your access.mdb is correct.
Then also make sure that if your supplying 3 parameters to your insert statement (in your case, the #NAME, #PASSWORD, #SALT), you must also have a matching column each for those 3 parameters to assign to.
string cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=access.mdb";
OleDbConnection c = new OleDbConnection(cs);
string Name = txtName.Text;
string PW = txtHash.Text;
string Salt = txtSalt.Text;
try
{
c.Open();
string s = "INSERT INTO regulate(NAME, PASSWORD, SALT) Values (#NAME, #PASSWORD, #SALT)";
using (OleDbCommand cmd = new OleDbCommand(s, c))
{
cmd.Parameters.AddWithValue("#NAME", Name);
cmd.Parameters.AddWithValue("#PASSWORD", PW);
cmd.Parameters.AddWithValue("#SALT", Salt);
cmd.ExecuteNonQuery();
MessageBox.Show("DATA ADDED");
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
c.Close();
}
I'm diving head first into both C# and Access databases. This is all brand new to me, so I have a small test database set up to work with a small template. I'm trying to figure out why I keep getting a syntax error that is triggered by the ExecuteNonQuery() method. Any help and insight would be appreciated.
Edit: SOLVED: This is the working code for this situation. All help was greatly appreciated!
public void addToDb()
{
String first = "John";
String last = "Doe";
String testPath = GVar.TEST_FILEPATH + GVar.TEST_DATABASE;
String strCommand = "INSERT INTO ID ([First], [Last]) Values(#First, #Last)";
OleDbConnection dbTest = null;
OleDbCommand cmd = null;
try
{
dbTest = new OleDbConnection(GVar.OLE_DB_WRITE + testPath);
dbTest.Open();
cmd = new OleDbCommand(strCommand, dbTest);
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();
Console.WriteLine("Data Added");
}
catch (Exception ex)
{
Console.WriteLine("Db Test: " + ex.Message);
}
dbTest.Close();
}
From OleDbCommand.Parameters property
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM
Customers WHERE CustomerID = ?
Therefore, the order in which
OleDbParameter objects are added to the OleDbParameterCollection must
directly correspond to the position of the question mark placeholder
for the parameter in the command text.
I don't see anything wrong in your INSERT statement other than this.
cmd.CommandText = "INSERT INTO Identity ([First],[Last]) VALUES(?, ?)";
cmd.Parameters.AddWithValue("#First", first);
cmd.Parameters.AddWithValue("#Last", last);
cmd.ExecuteNonQuery();