I don't get it!
I'm doing a simple insert in an access db.
static void EcrireDansBD()
{
//Connection a la BD
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=me.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
//works
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV) VALUES (1,2,3)";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,'ok')";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,ok)";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,\"ok\")";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Here is the table:
alt text http://img1.imagilive.com/0810/Capturee43.PNG
Help?
DESC is a reserved keyword which is used for ordering (ORDER BY column ASC/DESC).
you have to quote it: use [DESC] instead
Related
I'm trying to get two data(GenreID & GameID) from two different tables(genre & games) and insert them into another table(games_genre). However, it will close the connection to the database after inserting the GenreID successfully even though i had created another new connection to the database.
I have tried to create connection1 and connection2 to the same database. Connection1 is used to insert GenreID and connection2 is used to insert GameID
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
String gametitle = request.getParameter("gametitle");
String [] checkbox1 = request.getParameterValues("checkbox");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
Connection conn2 = DriverManager.getConnection(connURL);
Statement stmt = conn.createStatement();
if (checkbox1!= null){
for(String s: checkbox1){
String sqlStr2 = "Select * FROM genre WHERE GenreName='" + s + "'";
ResultSet rs = stmt.executeQuery(sqlStr2);
while(rs.next()){
String genreid = rs.getString("GenreID");
String sqlStr3 = "INSERT INTO games_genre(GenreID) VALUES ('" + genreid + "')";
int j = stmt.executeUpdate(sqlStr3);
if (j>0) {
out.println("Adding GenreID Successfully!");}
}
}
}
conn.close();
Statement stmt2 = conn2.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
String gameid = rs2.getString("GameID");
String sqlStr5 = "INSERT INTO games_genre(GameID) VALUES ('" + gameid + "')";
int k = stmt2.executeUpdate(sqlStr5);
if (k>0) {
out.println("Adding GameID Successfully!");
}
}
conn2.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Adding Game Successfully! Adding GenreID Successfully! Error :java.sql.SQLException: Operation not allowed after ResultSet closed
I don't understand that why do you need to create two Connection as you need to access same database . So ,just create multiple Statement to execute multiple query like below :
Statement stmt=null;
Statement stmt2=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
stmt = conn.createStatement();
if (checkbox1!= null){
....
}
<!--using same conn object -->
stmt2 = conn.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
...
}
<!--finally close connection-->
conn.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Note : Also try using PreparedStatement for preventing from Sql Injection as concatenating values into a query string is unsafe .
MySqlCommand command = new MySqlCommand(selectCmd, myConnection);
command.CommandText = "SELECT idtolistsubsoorten FROM `vogelsoort` WHERE id= MAX (id)and vogelsoort.naam =#vogelsoortnam";
command.Parameters.Add("#vogelsoortnaam", MySqlDbType.VarChar).Value = vogel.Soortnaam;
reader = command.ExecuteReader();
reader.Read();
while (reader.Read())
{
string idpape = reader.;
subid = Convert.ToInt64(idpape);
}
the reader keeps returning an null value
Your SQL query has a mistake: There are two FROM commands:
SELECT idtolistsubsoorten
FROM `vogelsoort`
WHERE id= MAX (id)
FROM `vogelsoort`
and vogelsoort.naam = #vogelsoortnam
Try using this one instead:
SELECT idtolistsubsoorten
FROM `vogelsoort`
WHERE id= MAX (id)
and vogelsoort.naam = #vogelsoortnam
Also, you can try executing the query in your dbms before running it in PHP, this way you will have an error message with more verbose.
are you mistaking in query you should write single or double quotas when you use string
command.CommandText = "SELECT idtolistsubsoorten FROM `vogelsoort` WHERE id= MAX (id) and vogelsoort.naam =#vogelsoortnam";
I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).
This is my function. It gets two parameter id of the product and a name. the function delete with MySQL command a row in a database. I know the that there are missing lines in my code, I'm stuck and I don't know how to finish it. I also know that my SQL line is not correct. I'm not sure if combined the String "name" right.
public static deletePro(int cat, String name) {
DB db = new DB();
String sql = "delete from products where pname=+'name' and catid=" + cat;
ResultSet rs = db.getResultSet(sql);
try {
while (rs.next()) {
Products prod = new Products();
prod.setNamePro(rs.getString(name));
prod.setAmount(rs.getInt(cat));
}
rs.close();
db.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
return
}
String sql = "delete from products where pname=+'name' and catid=" + cat;
This should be:
String sql = "DELETE FROM products WHERE pname='" + name + "' and catid = " + cat;
And the preferred way is to use PreparedStatement, which would alleviate the pain of string manipulation in your query by using placeholders:
String sql = "DELETE FROM products WHERE pname= ? and catid = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, cat);
ps.executeUpdate();
Hope this helps.
im working in mvc and use sql command to insert data to my
database.
what i try to do is insert into 2 tables which one of them
have the foreign key from the other.
how can i build my sql query to make a condition on insert
into the table Image, insert the id in the foreignkey column
in the table Content.
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("insert into Image(FileName)");
sql.Append("values (#FileName)");
SqlCommand cmd2;
System.Text.StringBuilder sql2 = new System.Text.StringBuilder();
sql.Append("insert into Code(Html,JsCode,Id_Img)");
sql.Append("values (#Html, #JsCode, #Id_Img)");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add("#FileName", SqlDbType.VarChar).Value = myfilename;
int FileId = (int)cmd.ExecuteScalar();
cmd2 = new SqlCommand(sql2.ToString(), cn);
cmd2.Parameters.Add("#Html", SqlDbType.VarChar).Value = mydiv;
cmd2.Parameters.Add("#JsCode", SqlDbType.VarChar).Value = DBNull.Value;
cmd2.Parameters.Add("#Id_Img", SqlDbType.Int).Value = FileId;
cmd2.ExecuteNonQuery();
cn.Close();
}
I think you can use ExecuteScalar() instead ExecuteNonQuery() to get the Scope_identity() value from the server like below and add that FileId to the second query.
using (SqlConnection cn = new SqlConnection("your_connection_string"))
{
string sql1 = "insert into Image(FileName) values (#FileName); " +
"SELECT CAST(scope_identity() AS int)";
string sql2 = "insert into Code(Html,JsCode,Id_Img) values (#Html, #JsCode, #Id_Img)";
int FileId = 0;
using (SqlCommand cmd = new SqlCommand(sql1,cn))
{
cmd.Parameters.AddWithValue("#fileName", myfilename);
cn.Open();
FileId= (int)cmd.ExecuteScalar();
}
}