Insertion in Excel failed - java

I tried inserting data into excel sheet using Java and ODBC, my URL is correct, the query to insert the data is executing, but the values are not inserted into excel sheet, i have made connection to commit and close. kindly help!
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:excelDsn;readonly=false;");
ps = con.prepareStatement("insert into [Sheet1$](FirstName, LastName) values (?,?)");
ps.setString(1, "AA");
ps.setString(2, "BB");
ps.execute();
con.commit();
con.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

for DDL statements like insert,delete and update use ps.executeUpdate();
As your case is to insert so replace ps.execute(); with ps.executeUpdate();

Related

Driver not found

I am using SQL Server 2018 and JDK 8.0 along with NetBeans. While connecting to the SQL Server, I am getting a SQL Exception as shown in the img
enter image description here
I am using the following code:
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Connection establishment
Connection con=DriverManager.getConnection("jdbc:sqlserver//DESKTOP-CU5U75J\\SQLSERVER1;","","");
//Statement Object
Statement st=con.createStatement();
//For DML use executeUpdate method of Statement Class
st.executeUpdate("insert into Employee (Employee_Id, Employee_Name) values ("+Integer.parseInt(idTF.getText())+","+nameTF.getText()+")");
//Commit Statement
con.commit();
JOptionPane.showMessageDialog(this, "Message", "The Data is Entered", JOptionPane.INFORMATION_MESSAGE);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Employe.class.getName()).log(Level.SEVERE, null, ex);
}
You have missed colon ':' in your jdbc url,
Connection con=DriverManager.getConnection("jdbc:sqlserver://DESKTOP-CU5U75J\\SQLSERVER1;integratedSecurity=true","","");
It was jdbc:sqlserver//DESKTOP-CU5U75J\\SQLSERVER1; which was supposed to be jdbc:sqlserver://DESKTOP-CU5U75J\\SQLSERVER1;
Also, I suggest you to use PreparedStatement to insert your records.
String sql="insert into Employee (Employee_Id, Employee_Name) values (?,?)";
PreparedStatement stmt=con.prepareStatement(sql);
stmt.setInt(1, Integer.parseInt(idTF.getText()));
stmt.setString(2, nameTF.getText());
stmt.executeUpdate();

how can i insert image in matisse database using SQL query?

i have to insert an image into the matisse database. how can i insert it through sql insert statement in java?
You can use a java.sql.PreparedStatement to insert a blob into your database.
Example code:
try{
Connection con = getYourDatabaseConnection();
PreparedStatement statement = con.prepareStatement("INSERT INTO YOUR_TABLE(YOUR_BLOB_COLUMN) VALUES (?)";
statement.setObject(1, yourImage);
statement.execute();
} catch(SQLException e){
e.printStackTrace();
}

Syntax for SQL statement using mysql database

public void insertTags(Elements[] elements) {
Connection con = (Connection) DbConnection.getConnection();
try {
String sql = "insert into htmltags(source) values(?),(?),(?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, elements[0].toString());
ps.setString(2, elements[1].toString());
ps.setString(3, elements[2].toString());
int rs = ps.executeUpdate(sql);
System.out.println("Data inserted" + rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
is this a valid syntax for Prepared statement.
This is your problem:
int rs = ps.executeUpdate(sql);
From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:
int rs = ps.executeUpdate(); // no parameter
Also no need to cast the result of prepareStatement to PrepareStatement
To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :
String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
for (Elements element : elements) {
ps.setString(1, element.toString());
ps.addBatch();//Add a new batch for each Element
}
int[] result = ps.executeBatch();//Submits a batch of commands to the database
} catch (SQLException e) {
e.printStackTrace();
}

Verify if the register already exeist

I don't have much experience in using JAVA with SQL Server or any other database, so I'm having some trouble at the moment.
I have the following code:
public void insertProjeto(Planejado p){
String verifica="SELECT cd_projeto FROM PROJETO WHERE cd_projeto = ?";
String sqlInsert="INSERT INTO PROJETO (cd_projeto, ds_projeto) VALUES (?, ?)";
String projeto = p.getProjeto();
String nomeProjeto = p.getNomeProj();
PreparedStatement stmt;
try {
stmt = getDBConnection().prepareStatement(verifica);
stmt.setString(1, projeto);
ResultSet rs = stmt.executeQuery();
if (rs.equals("") || rs.equals(null)) {
System.out.println("------------------");
stmt = getDBConnection().prepareStatement(sqlInsert);
stmt.setString(1, projeto);
stmt.setString(2, nomeProjeto);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
My goal is insert a register without duplicates, but for some reason my "if" isn't working.
Can anybody help me find out why?
Thanks in advance
When obtaining a ResultSet, you must call its next() method to have it progress to the first row of data if any. In case there is no data in the ResultSet object, rs.next() will return false.
There are better ways to prevent duplicates on SQL tables depends on what SQL server you're using (MS SQL, MySQL etc.)
If you're using MySQL, you can make cd_projeto a primary key and call REPLACE INTO instead of INSERT INTO, it will result in updating the record for cases it exist and inserting a new one when it doesn't.
Solved.
try {
stmt = getDBConnection().prepareStatement(verifica);
stmt.setString(1, projeto);
ResultSet rs = stmt.executeQuery();
while(!rs.next()) {
System.out.println("------------------");
stmt = getDBConnection().prepareStatement(sqlInsert);
stmt.setString(1, projeto);
stmt.setString(2, nomeProjeto);
stmt.executeUpdate();
break;
}
} catch (SQLException e) {
e.printStackTrace();
}
Don't know if it's the best way to do it, but works.
Thank you for the tips

MySQLSyntaxError inserting into MySQL database

I would like to insert data into the MySQL database that I am using.I get this ERROR.This is my code:
public boolean insertValues(String gisuniqkey,String objtype,String objkey,String lat,String lng)
{
int rc=-1;
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
//lots of String concatenation,very expensive...BAD...use StringBuilder instead
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values("+gisuniqkey+","+objtype+","+objkey+","+lat+","+lng+");";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rc>0?true:false;
}
I think the insert statement should be like this, Use single quotes around the values:
"Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values('"+gisuniqkey+"','"+objtype+"','"+objkey+"','"+lat+"','"+lng+"');";
Edit
Try it yourself in a command. What will work:
Option 1:
INSERT INTO ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE)
VALUES(asdasd,asdasd,asdasd,asdasd);
Option 2:
INSERT INTO ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE)
VALUES('asdasd','asdasd','asdasd','asdasd');
I would think that option 2 will work
Edit 2
But as mention in the comment. Using the prepare statement is recommended. Because this is open for sql injections
Reference:
SQL injection
JDBC PreparedStatement Example – Insert A Record
You should use PreparedStatements to avoid problems with building query strings.
PreparedStatement statement = null;
String insertSql = "Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values (?,?,?,?,?)";
conn.setAutoCommit(false);
statement = conn.prepareStatement(insertSql);
statement.setString(1, gisuniqkey);
statement.setString(2, objtype);
statement.setString(3, objkey);
statement.setString(4, lat);
statement.setString(5, lng);
con.commit();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values('"+gisuniqkey+"','"+objtype+"','"+objkey+"','"+lat+"','"+lng+"');";
Although, I would suggest you inject variable values using prepared statement.

Categories

Resources