I’m trying to write a method to get the string from the SQL INSERT query to the DB, with an input array as the number of columns using JDBC:
public String methodtest(String ListofColumns)
{
String query = "INSERT INTO" + TableName + "(" + ListOfColumns + ")";
try
{
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
While (rs.next())
{
String result = rs.getString(query);
System.out.println("The SQL query is " + result);
}
}
catch (SQLException sqlEx)
{
e.printStackTrace();
}
finally
{
rs.close();
}
}
Can you see any mistake?
Thanks, Monkawee, for the advice.
You can use the following pattern:
public string methodtest(Array listofcolumns)
{
try{
<Connection string path>
<DB connection method>
<Query string>
<Execution>
<Reset Object>
}
catch(SQLException sqlEx){
// handle exception
}
catch(Exception ex){
// handle other exceptions if any
}
finally{
<Close connection and other resources like PreparedStatement>
}
}
Related
So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}
I having a problem to run below Java code. I couldn't find the DB.java class.
ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
System.out.print(rs.getString("pid"));
System.out.print(rs.getString("name"));
System.out.print(rs.getString("price"));
System.out.print(rs.getString("ava_qty"));
}
I'm using Glassfish server. Can someone help me to write the DB.java class?
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:
https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm
Example code for future reference:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
I'm trying to insert in postgresql db date, but when I'm inserting it, I'm getting this error:
Error occurred while INSERTING operation: org.postgresql.util.PSQLException: ERROR: column "text that i wrote" does not exist"
I don't understand what did I code wrong that, program tries to find column in values?
But when I try to output this table, it outputs without errors
WORKERDAO class
public static void insertWrk(String name, String post) throws SQLException, ClassNotFoundException {
//Declare a INSTERT statement
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
//Execute INSTERT operation
try {
DBUtil.dbExecuteUpdate(updateStmt);
} catch (SQLException e) {
System.out.print("Error occurred while INSTERING Operation: " + e);
throw e;
}
}
DBUTIL class
public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
//Declare statement as null
Statement stmt = null;
try {
//Connect to DB
dbConnect();
//Create Statement
stmt = conn.createStatement();
//Run executeUpdate operation with given sql statement
stmt.executeUpdate(sqlStmt);
} catch (SQLException e) {
System.out.println("Проблема в выполнение executeUpdate операции : " + e);
throw e;
} finally {
if (stmt != null) {
//Close statement
stmt.close();
}
//Close connection
dbDisconnect();
}
}
WorkerController Class
#FXML
private void insertWorker (ActionEvent actionEvent) throws SQLException, ClassNotFoundException {
try {
WorkerDAO.insertWrk(nameText.getText(),postCombo.getSelectionModel().getSelectedItem());
} catch (SQLException e) {
System.out.println("Problem occurred while inserting worker " + e);
throw e;
}
}
You need to put quotes around the data you're inserting:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
Should be:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"('"+name+"',"'+post+'");";
Be aware that you're risking SQL Injection attacks using this method, see about using a parameterised insert. This site lists a bit more detail.
I am using this code to create a login webservice to database
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){};
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = '+name+' and prenom = '+lastname+' ";
st.close();
cn.close();
System.out.println("success");
return "login";
}
}
My code is working but I don't know how to extract the result of the sql request ( here id )
Are there any suggestions to this issue? Please help!
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){
e.printStackTrace();
}
try {
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = "+name+" and prenom = "+lastname+" LIMIT 1";
ResultSet res = st.executeQuery(req);
if(res.first()) {
String id = res.getString("id");
System.out.println("id = "+id);
} else {
System.out.println("not found foo!");
}
}
catch (SQLException s){
s.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
st.close();
cn.close();
}
return "login";
}
}
On executing the follwing code i am getting error java.sql.SQLException: ResultSet is closed
public class SavePoints {
public void extract(ResultSet rs)
{
int c;
try {
while(rs.next())
{
c = rs.getInt("id");
String d=rs.getString("name");
String e=rs.getString("city");
String f=rs.getString("state");
String g=rs.getString("country");
//Displaying values
System.out.println("ID is:"+c+"\tName is:"+d+"\tCity is:"+e+"\tState is:"+f+"\tCountry is:"+g);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
SavePoints spobj=new SavePoints();
try {
Connection con=DriverManager.getConnection("jdbc:odbc:Divya", "SYSTEM", "tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from publishers");
spobj.extract(rs);
//DatabaseMetaData databaseMetaData = con.getMetaData();
//System.out.println(databaseMetaData.getDriverMajorVersion());
//Savepoint sp=con.setSavepoint("Deleting Rows");
st.execute("delete from publishers where id=104");
//con.rollback(sp);
spobj.extract(rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What is the error? I cannot find it. Please let me know. I am a newbie.. so please explain in simple terms. I am grateful for your help. Thanks :)
you have called spobj.extract(rs); twice ,
first time when this function executes resultset moves to last because you are using rs.next()..
to achieve this you have use scrollable resultset
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
and for next call of spobj.extract(rs); reverse the call of resultset by rs.previous()