I have searched to insert a value from application java into a mysql table.
Following there's my code. The result of it is a long row of error, but the first row is: java.sql.SQLException: Before start of result set
Connection con = null; //oggetto di connessione
try {
Class.forName("com.mysql.jdbc.Driver"); //connessione
con = DriverManager.getConnection("jdbc:mysql://localhost/autonoleggio", "root", "");//connessione vera e propria
//quarto va cambiato col nome del database creato
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM dati"); // persone ->tabella presente nel database
if(targa.getText().equals(rs.getString("Targa")))
{
Statement insideStatement = con.createStatement();
ResultSet insideResultsSet = insideStatement.executeQuery(
"INSERT INTO dati (Cliente) VALUES ('"+inserisci.getText()+"');"
);
/*String query;
query="INSERT INTO dati (Cliente) VALUES ('"+inserisci.getText()+"');";
PreparedStatement statement = con.prepareStatement(query);
statement.executeUpdate();
statement.close(); */
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(con != null) {
con.close();
}
}
The ResultSet object is sort of an iterator on the result returned from the database. Like any iterator, it starts before the first element, and needs to be advanced to point to it. In short, you're missing a call to ResultSet#next():
ResultSet rs = st.executeQuery("SELECT * FROM dati");
if (rs.next() && targa.getText().equals(rs.getString("Targa"))) {
// Here -^
Related
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();
}
I have two methods below for checking if a match is in the database and if not if would call the insert method. My program has to go through thousands of rows and it takes a very long time. Am I doing this incorrectly? Anything I can do to significantly make this faster?
public Boolean isMatchIdInDatabase(String matchId) throws SQLException
{
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Boolean exists = false;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("SELECT COUNT(*) FROM match where match_id = ?");
pst.setString(1, matchId);
rs = pst.executeQuery();
while (rs.next())
{
exists = rs.getBoolean(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
pst.close();
rs.close();
conn.close();
}
return exists;
}
public Boolean insertMatchId(String matchId, String name, Timestamp birthdate, String bio, String accountId) throws SQLException, ClassNotFoundException
{
Connection conn = null;
PreparedStatement pst = null;
Boolean exists = false;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("INSERT INTO match (match_id, name, birthdate, bio, account_id) values(?, ? , ?, ?, ?)");
pst.setString(1, matchId);
pst.setString(2, name);
pst.setTimestamp(3, birthdate);
pst.setString(4, bio);
pst.setString(5, accountId);
pst.executeUpdate();
}
finally
{
pst.close();
conn.close();
}
return exists;
}
Are you calling first isMatchIdInDatabase then insertMatchId for many records?
Possible duplicate: Efficient way to do batch INSERTS with JDBC
It is an expensive operation to open a connection and query for a single record. If you do that thousands of times, it gets very slow. You should try to restructure your query so that you only use one SELECT. Then you can collect the records which you have to insert and doing it with batch insert.
You could try changing your SQL query that inserts the row to insert only if the row isn't in the database by using WHERE NOT EXISTS.
This post seems to be relevant - I know it's for MySQL instead of PostgreSQL but the principles should be the same.
MySQL Conditional Insert
In my database bean I have a section of code which is below :
public Integer getTotalOrgPoints() {
try {
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
totalOrgPoints = rs.getInt(1);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return totalOrgPoints;
}
For the statement QUERY_TOTAL_ORG_SCORE if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = 1
It will return the value for that organisation but if I use
SELECT SUM(users.score)
FROM user_organisation_relationships
INNER JOIN users
ON user_organisation_relationships.user_id = users.id
WHERE organisation_id = ?
I get nothing does anyone know why this is happening for me?.
Add this line to bind values for prepared statement before executequery
stmt.setInt(1, 1);
Modified:-
PreparedStatement stmt = ConnectionHandler.getConnection().prepareStatement(QUERY_TOTAL_ORG_SCORE);
stmt.setInt(1, 1);
ResultSet rs = stmt.executeQuery();
(the Stored Procedure runs perfectly in MySQL Workbench and also retrieves the Rows)
Here is My Code :
ConnectionManager cm = new ConnectionManager();
java.sql.CallableStatement cstmt = null;
try
{
connect = cm.getConnection();
connect.createStatement();
String SQL = "{call getReportDetails ('"+ emailId +"','"+password+"')}";
cstmt = connect.prepareCall(SQL);
rs = cstmt.executeQuery(SQL);
int i = 0;
while(rs.next())
{
String element1 = rs.getString("description");
// -- some code --
}
}
catch(Exception e)
{
e.printStackTrace();
}
Delete the line with createStatement.
And (the error) do not use SQL as parameter of executeQuery.
(The overloaded version with an sql parameter is for the immediate, non-prepared statement version.)
Further close statement and result set; try-with-resources will do nice here.
try (CallableStatement cstmt =
connect.prepareCall"{call getReportDetails (?, ?)}")) {
cstmt.setString(1, emailId);
cstmt.setString(2, password);
try (ResultSet rs = cstmt.executeQuery()) {
int i = 0;
while (rs.next())
{
String element1 = rs.getString("description");
// -- some code --
}
}
}
In the general case for stored functions you might need to specify the result yourself:
cstmt.registerOutParameter(1, Types.INTEGER);
cstmt.registerOutParameter(2, Types.VARCHAR);
rs.getString(2);
But here you have a ResultSet.
CallableStatement cs = null;
try {
cs = connectionObject.prepareCall("{call getReportDetails (?, ?)}");
cs.setString(1, emailId);
cs.setString(2, password);
cs.execute();
ResultSet rs = cs.getResultSet();
while (rs.next()) {
System.out.println(rs.getString("columnLabel"));
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
//close statements
}
The following code doesn't show any error and the code executes but the data that is calculated and stored in rfv is not updated in the database.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
com.mysql.jdbc.Connection con = (com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3308/rk","root","root");
ResultSet rsfact=null;
PreparedStatement psfact=(PreparedStatement) con.prepareStatement("SELECT * FROM fact");
PreparedStatement psgraph=(PreparedStatement) con.prepareStatement("INSERT INTO graph values(?,?,?,?)");
int cp,ic,rc,fi,ct,tr;
while(rsfact.next())
{
cp=rsfact.getInt("1");
ic=rsfact.getInt("2");
rc=rsfact.getInt("3");
fi=rsfact.getInt("4");
ct=rsfact.getInt("5");
tr=rsfact.getInt("6");
int rfv;
rfv=(cp+ic+rc+fi+ct+tr)/6;
graph.setInt(1, rfv);
graph.executeUpdate();
}
}
catch(Exception e){
System.out.println(e);
}
I checked the code and everything seems to be fine for me but i couldn't figure out the reason for the data which is not inserted into the table.
I get the following when this is executed
java.lang.NullPointerException
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
com.mysql.jdbc.Connection con = (com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3308/rk","root","root");
ResultSet rsfact=null;
ResultSet rsfault=null;
ResultSet rspriority=null;
ResultSet rsreq=null;
PreparedStatement psfact=(PreparedStatement) con.prepareStatement("SELECT * FROM fact");
PreparedStatement psfault=(PreparedStatement) con.prepareStatement("SELECT * FROM fault");
PreparedStatement pspriority=(PreparedStatement) con.prepareStatement("SELECT * FROM priority");
PreparedStatement psreq=(PreparedStatement) con.prepareStatement("SELECT * FROM req");
PreparedStatement graph=(PreparedStatement) con.prepareStatement("INSERT INTO gr values(?)");
int cp,ic,rc,fi,ct,tr;
rsfact = psfact.executeQuery();
rsfault=psfault.executeQuery();
rspriority=pspriority.executeQuery();
rsreq=psreq.executeQuery();
while(rsfact.next())
{
cp=rsfact.getInt(1);
ic=rsfact.getInt(2);
rc=rsfact.getInt(3);
fi=rsfact.getInt(4);
ct=rsfact.getInt(5);
tr=rsfact.getInt(6);
int rfv;
rfv=(cp+ic+rc+fi+ct+tr)/6;
graph.setInt(1, rfv);
graph.executeUpdate();
}
while(rsfault.next()){
cp=rsfact.getInt(1);
fic=rsfact.getInt(2);
frc=rsfact.getInt(3);
ffi=rsfact.getInt(4);
fct=rsfact.getInt(5);
ftr=rsfact.getInt(6);
int tsfv;
tsfv=((fcp*2)+(fic*3)+(frc*4)+(ffi*3.14)+(fct-4)+(ftr+9))/6;
graph.setInt(2, tsfv);
graph.executeUpdate();
}
}
you are not instatiating rsfact(ResultSet object) and trying to invoke methods of result set thus NULLPOINTEREXCEPTION.
ResultSet rsfact=null; // **rsfact is null**
int colCount=1;
PreparedStatement psfact=(PreparedStatement) con.prepareStatement("SELECT * FROM fact");
PreparedStatement psgraph=(PreparedStatement) con.prepareStatement("INSERT INTO graph values(?,?,?,?)");
int cp,ic,rc,fi,ct,tr;
rsfact = psFact.executeQuery(); **// this instantiates ResultSet, if you dont includee this statement rsfact would still be null.**
while(rsfact.next()) // **if rsfact null and u execute this line it would throw nullpointer exception(cuz rsfact is null)**
{
cp=rsfact.getInt("1");
ic=rsfact.getInt("2");
rc=rsfact.getInt("3");
fi=rsfact.getInt("4");
ct=rsfact.getInt("5");
tr=rsfact.getInt("6");
int rfv;
rfv=(cp+ic+rc+fi+ct+tr)/6;
graph.setInt(colCount, rfv);
colCount++;
}
graph.executeUpdate();