I'm getting a syntax error in INSERT INTO statement and I can't figure out why. I've checked several different SO questions that were almost exactly the same as my problem and after changing my code this way and that way it still isn't working.
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", oldDb);
var cnn = new OleDbConnection(cnnStr);
cnn.Open();
//make new access table
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = cnn;
command.CommandText = String.Format("CREATE TABLE [{0}] ([Tag] string, [Text] string)", newTable + "_Diff");
try
{
command.ExecuteNonQuery();
}
catch
{
//table already exists
}
}
//fill access table
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = cnn;
command.CommandText = String.Format("INSERT INTO [{0}] (Tag, Text) VALUES (?, ?)", newTable + "_Diff");
command.Parameters.Add(new OleDbParameter("Tag", ""));
command.Parameters.Add(new OleDbParameter("Text", ""));
for (int i = 0; i < (diffText.Length - 1); i++)
{
command.Parameters["Tag"].Value = diffTag[i];
command.Parameters["Text"].Value = diffText[i];
command.ExecuteNonQuery();
}
}
cnn.Close();
Creating the table is working so I know there's not a problem with my connection, there's just something it doesn't like about my insert statement.
In your insert command put text inside a square bracket, "text" is a keyword
command.CommandText = String.Format("INSERT INTO [{0}] (Tag, [Text])
VALUES (?, ?)", newTable + "_Diff");
also make sure you are including your values with single quote
values ('?','?')
hope this works
Related
I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)
My question is like the title:
how to get 1 word of a row from an table in a database to another table using an username that exists in both tables.
This is what i tried
var word = db.QueryValue("SELECT wordlist FROM tableold WHERE username IN(SELECT username FROM tablenew)");
var insertCommand = "INSERT INTO tablenew (wordlist) VALUE(word)";
db.execute(insertCommand, word);
With db as my database ofcourse.
The problem here is that" word" can't be inserted here because thats not allowed.
My question: is there a way to do this? Help would be appreciated!
Just use insert . . . select:
INSERT INTO tablenew (wordlist)
SELECT wordlist
FROM tableold
WHERE username IN(SELECT username FROM tablenew);
Maybe try this approach:
DataTable words = new DataTable();
string word = string.Empty;
using (SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;
cmd.CommandText = #"SELECT wordlist FROM tableold WHERE username IN(SELECT username FROM tablenew)";
SqlDataAdapter adap = new SqlDataAdapter();
adap.SelectCommand = cmd;
adap.Fill(words);
}
if (words != null && words.Rows.Count > 0)
{
word = words.Rows[0].Field<string>("wordlist"); // for example
using (SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#word", word);
cmd.CommandText = #"INSERT INTO tablenew(wordlist) VALUE(#word)";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
the simple awnser was to put #0 at the place of word inside the insert into query
I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}
I have this stored procedure:
Insert into dbo.file_row (file_sub_type) values (#file_sub_type)
DECLARE #result int;
SET #result = SCOPE_IDENTITY()
RETURN #result;
This works fine to return the id in SSMS. However, when I call it from C#, it returns -1.
var connection = GetSqlConnection();
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "InsertInto_file_row";
command.Parameters.Add(new SqlParameter("#file_sub_type", fileType));
int result = command.ExecuteNonQuery();
connection.Close();
return result;
I don't see what I am doing wrong. I just need the Id of the inserted record.
Greg
Check the docs on ExecuteNonQuery():
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
(Emphasis mine)
If you want to get information back, you have a couple options:
Change RETURN to SELECT and ExecuteNonQuery() to ExecuteScalar()
Use an OUTPUT parameter
To add on to Joel's response
Try ExecuteScalar instead
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. (Overrides DbCommand.ExecuteScalar().)
This will help you. The function returns the new Identity column value if a new row was inserted, 0 on failure. It is from MSDN
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
public int AddProductCategory(string newName, string connString)
{
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Name", newName);
con.Open();
latestInsertedId = (int)cmd.ExecuteScalar();
con.Close();
}
return latestInsertedId ;
}
}
I wrote some code that takes some values from one table and inserts the other table with these values.(not just these values, but also these values(this values=values from the based on table))
and I get this error:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.`
here's the code. I don't know what i've missed.
string selectedItem = comboBox1.SelectedItem.ToString();
Codons cdn = new Codons(selectedItem);
string codon1;
int index;
if (this.i != this.counter)
{
//take from the DataBase the matching codonsCodon1 to codonsFullName
codon1 = cdn.GetCodon1();
//take the serialnumber of the last protein
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
dr.Read();
index = dr.GetInt32(0);
//add the amino acid to tblOrderAA
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) "
+ " values (?, ?)";
using (OleDbCommand command = new OleDbCommand(insertCommand, connection))
{
connection.Open();
command.Parameters.AddWithValue("orderAASerialPro", index);
command.Parameters.AddWithValue("orderAACodon1", codon1);
command.ExecuteNonQuery();
}
}
}
EDIT:I put a messagebox after that line:
index = dr.GetInt32(0);
to see where is the problem, and I get the error before that. I don't see the messagebox
Your SELECT Command has a syntax error in it because you didn't enclose it with quotes.
Change this:
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ;
OleDbCommand getSerial = new OleDbCommand(last, conn);
OleDbDataReader dr = getSerial.ExecuteReader();
to
string last = "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = ?";
OleDbCommand getSerial = new OleDbCommand(last, conn);
getSerial.Parameters.AddWithValue("?", this.name);
OleDbDataReader dr = getSerial.ExecuteReader();
This code is example from here:
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Try to do the same as in the example.