I try to read out a table and write it into a csv file.
while (rs2.next())
{
Enumeration<String> en = sqlfields.keys();
while (en.hasMoreElements())
{
String field = en.nextElement();
String value = rs2.getString(field);
bw.write(Kapseln + value + Kapseln + Trennzeichen);
}
bw.newLine();
cur++;
}
But if the field is type: DateTime, I get this error message:
java.sql.SQLException: Cannot convert value
'0000-00-00 00:00:00' from column 12 to TIMESTAMP.
Why Java tries to convert to a Timestamp?
I like to get the value as String => rs2.getString(field)
set
zeroDateTimeBehavior="convertToNull"
in your JDBC connection properties. ref: http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-configuration-properties.html
EDIT that would make your connection string look like this:
jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull
The following code is working fine. Check your code with this...
The fourth field of the emp table is jDate which is a DateTime data type.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","test");
System.out.println("Connection is : " + con);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from emp");
//stmt = con.createStatement();
while(rs.next()) {
String value = rs.getString(4);
System.out.println(value);
}
System.out.println("Connection is : " + con);
con.close();
Related
I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1
I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.
try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
FileReader file1 = new FileReader("resources/Test.txt");
BufferedReader buffer1 = new BufferedReader(file1);
String read;
while ((read = buffer1.readLine()) != null) {
String[] row = read.split(",");
String fName = row[0];
String sName = row[1];
String DOB = row[2];
String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";
ps = con.prepareStatement(insert);
ps.executeUpdate();
ps.close();
}
} catch (Exception ex) {
System.out.println(ex);
}
As mentioned in the comments, don't quote the column names.
The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.
Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");
Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.
try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
ps.setString(0, fName);
ps.setString(1, sName);
ps.setString(2, DOB);
ps.execute();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
I'm trying to get the new id when inserted new data in database table, but I got:
ORA-01008: not all variables bound
I'm doing it from a Java SE project,
public ResultSet ejecutarConsulta(String instruccionSql){
rs = null;
try {
st = con.createStatement();
rs = st.executeQuery(instruccionSql);
System.out.println("Consulta Exitosa");
} catch (SQLException e) {
System.out.println("Error en la Consulta: "+e.getMessage());
}
return rs;
}
And the String "instruccionSql" that i'm passing is
insert into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO)
values ('22323','asfa','Administrador','123456','0')
RETURNING ID INTO :temp
I have the corresponding trigger and Seq to generate the table autoincrement id.
Use CallableStatement and register the OUT parameter.
This is an excellent opportunity to register the IN parameters too.
String mySql = "DECLARE x NUMBER; BEGIN "
+ " insert into Usuario(DOCUMENTOIDENTIDAD,NOMBRE,CARGO,CONTRASENA,PERMISO) "
+ " values (?,?,?,?,?) "
+ " RETURNING ID INTO x;"
+ " ? := x;"
+ "END; ";
CallableStatement cal = conn.prepareCall(mySql);
cal.setString(1, "22323");
cal.setString(2, "asfa");
cal.setString(3, "Administrador");
cal.setString(4, "123456");
cal.setString(5, "0");
cal.registerOutParameter(6, java.sql.Types.INTEGER);
cal.executeQuery();
Integer newId = cal.getInt(6);
you are attempting to use a bind variable (:i) that is not bound to a value.
I use mysql workbench and netbeans
I have a table in mysql: Products that contains productsquantity=50 for example
in java, I want to add a value from text field to the database ( 50+value to add) please help, I use this code and didn't work
String url = "jdbc:mysql://localhost:3306/joebdd";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "12345";
//Error is here:
String sql = "UPDATE Produit " + " SET Quantity =
Quantity+'"+Integer.parseInt(jTextField4.getText())+"' " + "WHERE ProductName = ? " ;
try
{
Class.forName(driver).newInstance();
Connection conn = (Connection)DriverManager.getConnection(url,user,pass);
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, jTextField4.getText());
pst.setString(2, jTextField1.getText());
pst.executeUpdate();}
catch( Exception e){
JOptionPane.showMessageDialog(null, e);
}
Getting rid of the single quotes around the quantity that you're adding would fix your problem.
A better solution would be to use a ? in place of that quantity, and set it with setInt. So the SQL would be
UPDATE Produit SET Quantity = Quantity + ? WHERE ProductName = ?
and the line to set it would be
pst.setInt(1, Integer.parseInt(jTextField4.getText()));
I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}
i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!