public bool location()
{
string OUI = "OUI";
SqlConnection con = new SqlConnection(#"Data Source=WIN-218NC1F1FE2\SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string v = Convert.ToString(maxId);
//correct
SqlCommand q = new SqlCommand("insert into reservation(location) values('" + OUI + "') where id_reservation ='"+ maxId + "'", con);
SqlDataReader da = q.ExecuteReader();
return true ;
}
the probleme was in command where : Incorrect syntax near the keyword 'where'.
help !!!
You can not have a where clause in an insert statement. That's all that is to it. If you want to insert, remove the where clause. If you need to update records that match a condition, don't use insert but update.
Also, if you're not really interested in the result of a query, don't use ExecuteReader but ExecuteNonQuery.
Thorsten answer is clear an complete I am just adding the code for each case:
SqlConnection con = new SqlConnection(#"Data Source=WIN-218NC1F1FE2\SQLEXPRESS;Initial Catalog=projet;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select max(id_reservation) from reservation");
cmd.Connection = con;
Int32 maxId = (Int32)cmd.ExecuteScalar();
string ID=maxId.TOString();
//correct
/////INSERT
SqlCommand q = new SqlCommand("insert into reservation(location) values(#location,#ID)", con);
q.Parameters.AddWithValue( "#location",OUI);
q.Parameters.AddWithValue("#ID",ID);
q.ExecuteNonQuery();
return true ;
////////UPDATE
SqlCommand q = new SqlCommand("update reservation set location=#location where id_reservation =#ID", con);
q.Parameters.AddWithValue( "#location",OUI);
q.Parameters.AddWithValue("#ID",ID);
q.ExecuteNonQuery();
return true ;
Related
IWhat i wanna do
So I tried this code
but it coudnt get a connection with the Database. I the connection string is correct
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into [kunde]Vorname()values(#nm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Connection = con;
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "insert into [kunde]Nachname()values(#nmm)";
cmdd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmdd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
follow the following code. It inserts two columns into a table (tableName). Maintain proper space in SQL query as showing in below sample code. ALso, it's best practice to keep the code in a try-catch block to capture any error that occurs during DB operation.
try
{
SqlConnection con = new SqlConnection("server=localhost;uid=root;database=menucreator");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into tableName(column1,column2) values(#nm,#nmm)";
cmd.Parameters.AddWithValue("#nm", Vorname.Text);
cmd.Parameters.AddWithValue("#nmm", Nachname.Text);
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
if (a == 1)
{
MessageBox.Show("Dateien bitte");
}
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.ToString());
}
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 the below function
SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
int h = (int)cmd.ExecuteScalar() + 1;
txtID.Text = h.ToString();
cn.Close();
How to fix this Error:
Specified cast is not valid.
given your code I feel the easiest way to fix the logic is to edit the SQL to
select ISNULL(max(ID),0) from EP_PATTERNS
To better understand what this does you can run this SQL in SSMS:
DECLARE #table table (ID int);
SELECT MAX(ID) FROM #table;
SELECT ISNULL(MAX(ID), 0) FROM #table;
Whether table EP_PATTERNS contains any rows? Otherwise you a trying to cast NULL to int and fails.
You code should looks like:
SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
var value = (int?)cmd.ExecuteScalar();
int maxId = value.HasValue ? value.Value + 1 : 0; //Increase value or default it to zero
txtID.Text = maxId.ToString();
cn.Close();
Using coalesce you can achieve this:
con.Open();
cmd.Connection = con;
cmd.CommandText = "select coalesce(max(user_id),0)+1 from user_master";
int user_id = int.Parse(cmd.ExecuteScalar().ToString());
txt_user_id.Text = user_id.ToString();
con.Close();
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.
string databaseLocation = "|DataDirectory|\\Users.mdf";
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + databaseLocation + ";Integrated Security=True;User Instance=True";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = String.Format("SELECT * FROM Users WHERE Username = {0}", username);
command.CommandType = CommandType.Text;
command.Connection = sqlConnection;
sqlConnection.Open();
int numberOfRows = command.ExecuteNonQuery();
sqlConnection.Close();
return numberOfRows;
This should check the Users.mdf database for the number of occorances of the username. but im getting a "syntax error near Source" runtime error when it hits the ExecuteNonQuery. I cant find anything wrong... Please help :)
Your formatted sql statement is not including delimiters for the username:
command.CommandText = String.Format("SELECT * FROM Users WHERE Username = {0}", username);
sets the command text to something like:
SELECT * FROM Users WHERE Username = foo
This is easily corrected, but it would be better to use a SqlParameter:
command.CommandText = "SELECT * FROM Users WHERE Username = #username");
command.Parameters.AddWithValue("#username", username);
Also, ExecuteNonQuery will return -1 for the number of rows affected, since the select doesn't affect rows. Instead do:
command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = #username");
command.Parameters.AddWithValue("#username", username);
...
int numberOfRows = (int)command.ExecuteScalar();
Your code should be:
string databaseLocation = "|DataDirectory|\\Users.mdf";
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + databaseLocation + ";Integrated Security=True;User Instance=True";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT COUNT(*) FROM Users WHERE Username = #User";
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#User",username);
command.Connection = sqlConnection;
sqlConnection.Open();
int numberOfRows = command.ExecuteScalar();
sqlConnection.Close();
return numberOfRows;