What is the problem in this code? where it is update the all column values with the same last one .
public class dbconnection {
java.sql.Connection con;
java.sql.Statement st;
ResultSet rs;
public EncBean getConnection()throws SQLException{
EncBean encBean1 = new EncBean();
String v_url= "jdbc:oracle:thin:#192.168.2.138:1522:orcl2";
String v_username= "scott";
String v_password = "tiger";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(v_url,v_username,v_password);
System.out.println ("Connection to Oracle database was Established");
}
catch ( SQLException e)
{
e.printStackTrace();
}
return encBean1;
}
public EncBean selectRows()
{
EncBean encBean2 = new EncBean();
try
{
String SQLselect="select JOB_NAME from job";
st=con.createStatement();
rs=st.executeQuery(SQLselect);
while (rs.next()) {
encBean2.setName(rs.getString("JOB_NAME"));
}
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return encBean2;
}
public void updateRows(String updatedname){
try
{
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
ResultSet srs = stmt.executeQuery("select job_name from job " );
while (srs.next()) {
srs.updateString("job_name", updatedname);
srs.updateRow();
con.commit();}
System.out.println("An existing user was updated successfully!");}
catch(SQLException err){
System.out.println(err.getMessage());
}}}
This is the main
public class mainenc {
public static void main(String[] args) throws Exception{
dbconnection dbcon = new dbconnection();
EncBean encbeancon= dbcon.getConnection();
EncBean encBean5 = dbcon.selectRows();
enc concatinputs = new enc();
EncBean encBeanconcat = concatinputs.funconcat(encBean5.getName());
EncBean encBean4 = concatinputs.inputencryption(encBeanconcat.getConcatenatedData());
String vReserverbin= encBean4.getReversedBinary();
String ascistring= concatinputs.convertBinaryStringToString(vReserverbin);
dbcon.updateRows(ascistring);
}}
What is the problem in this code? where it is update the all column values with the same last one .
After updated method you should write list method again.
Try to take this example:
UPDATE tableB
SET tableB.value , tableA.value, tableB.value)
WHERE tableA.name = 'Joe'
It is kind of obvious: dbcon.updateRows(...) calls for the update method and that method does the job.
But as Erhan said, you don't get to see the result because you don't actually make use of updated records, e.g. show them etc. At least, you can check it out at the DB level if op is completed.
But I really disliked your comment:
plz can you do it for me?
You should do your own task and ask help when you need a hand. But never expect someone else to do your job mate.
Related
I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}
I'll try my best to make this as clear as possible since I'm new to Java. If there are parts which are unclear to you, please let me know. I apologize beforehand if the structure of my coding is messy.
I'm making a combobox event wherein if an item is selected (or changed), it will display items of that database and if the Update button is clicked, the program will connect to the database based on the item selected in the combobox.
The problem is that the variable cn after the if-else statement, has an error of "variable may have not been initialized".
Please note that I would like to focus on the condition since it is where I'm having difficulties and that the Update part is not a concern at this time.
private void btn_UpdateActionPerformed(java.awt.event.ActionEvent evt)
{
String value2 = (String) combobox_location.getSelectedItem();
String value4 = (String) combobox_category.getSelectedItem();
try
{
if(value2.equals(value4))
{
Connection cn = db.itemconnector.getConnection();
}
String sql = "UPDATE items set location = '"+value2+"' where id = '"+value4+"' " ; //Please ignore this line for the now
PreparedStatement ps1 = cn.prepareStatement(sql);
ps1.execute();
JOptionPane.showMessageDialog(null, "Update Successful");
PreparedStatement ps2 = cn.prepareStatement(ref);
ResultSet rs = ps2.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
System.out.println("Update Error!");
}
}
I have a package db that has itemconnector class for database connection and here is my code I've written in it. I hope I have provided all necessary details for your assistance. If you need more info, please let me know. Thank you.
package db;
import java.sql.*;
public class itemconnector {
/**
*
* #return
* #throws Exception
*/
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
public static Connection getConnection1() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales1","root","");
return cn;
}
public static Connection getConnection2() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales2","root","");
return cn;
}
}
i have been using this JDBC conection in all of my class that had to run query but i created a new class which i dont want the constructor with a parameter of the DConnection from JDBC Class(main Database Class).
but i keep on getting NullPointExceptions. Can anyway figur out what that problem may be.
Thanks.
public class UsersDao {
// associating the Database Connection objekt
private DConnector connector;
private final Connection myConn;
// Constructor
public UsersDao() throws CZeitExceptionHand,SQLException {
myConn = connector.getConnenction();
}
public boolean updateUsers(String mitarb, int mid) throws SQLException{
// PreparedStatement myStmt = null;
Statement stmt = myConn.createStatement();
try {
String myStmt = "SELECT Bly "
+ "" + mid + ";";
return stmt.execute(myStmt);
} finally {
close(stmt);
}
}
Example like this Method which is working but in different class
String[][] getAllTheWorkers(DConnector connector) throws CZeitExceptionHand {
try {
Connection connect = connector.getConnenction();
Statement stmt = connect.createStatement();
ResultSet result = stmt.executeQuery("SELECT ");
result.last();
int nt = result.getRow();
result.beforeFirst();
}
return results;
} catch (SQLException e) {
throw new CZeitExceptionHand("Error: " + e);
}
}
The object does not seem to be initialized.
Can you please post which method is not working and from where it is invoked ?
P.S : Unable to add a comment - that is why have answered !
Well, I'm trying to use SQLite in my Libgdx game, but don't know how.
public class Main {
public static void main(String[] args){
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = Game.TITLE;
config.width = Game.V_WIDTH * Game.SCALE;
config.height = Game.V_HEIGHT * Game.SCALE;
new LwjglApplication(new Game(), config);
}}
What I need to do in my main? lol
I've been looking for this but, all I can find is related to Android application.
I already have the driver in my ref libraries, and connection class..
What I usually do when using a database with an application, is make a ConnectionFactory, that returns a new connection to the database.
public class ConnectionFactory {
public static Connection getConnection() {
Connection con = null;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:test.db"); //change to whatever db you want
return con;
}
}
now we have a ConnectionFactory that can pump out connections to our database. Now when we want to interact with the database, you can get the connection appropriately. inside your main, it might look something like this:
public static void main(String[] args) {
Connection con = null;
String firstName = null, lastName = null;
try {
con = ConnectionFactory.getConnection();
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM myTable where myId = ?");
pstmt.setInt(1, /*some id here, ill put this as example:*/ 1234567);
//execute the query and put into result set so we can get the values.
ResultSet rs = pstmt.executeQuery();
//the resultset iterates through rows, by calling next
if( rs.next() ) //could be while(rs.next()) if expecting multiple rows
{
firstName = rs.getString("firstName"); //column name you want to grab here
lastName = rs.getString("lastName");
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally {
try {
con.close(); //dont forget to close your connection to database!
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
}
You will need to create tables within the SQLite database and insert records before you can do any interactions though, so keep that in mind.
can anyone please tell why the following update query which is working perfectly when executed directly from my SQLYog editor, but not executing from java. it is not giving any exception but not updating into the database.
this the update query
UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))
Java code
public static void main(String[] args) throws Exception {
int update = new Dbhandler().update("UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))");
}
public int update(String Query)throws Exception
{
try
{
cn=getconn();
stmt=(Statement) cn.createStatement();
n=stmt.executeUpdate(Query);
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
throw(e);
}
finally
{
cn.close();
}
return n;
}
public Connection getconn()
{
try
{
Class.forName(driver).newInstance();
String url="jdbc:mysql://localhost/kot?user=root&password=root";
cn=(Connection) DriverManager.getConnection(url);
}
catch(Exception e)
{
System.out.println("DBHandler ERROR:"+e);
}
return cn;
}
This is how I used to do it before I switched to Spring's JdbcTemplate framework. Maybe this will help. It looks very similar to yours.
public static int runUpdate(String query, DataSource ds, Object... params) throws SQLException {
int rowsAffected = 0;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ds.getConnection();
stmt = conn.prepareStatement(query);
int paramCount = 1;
for (Object param : params) {
stmt.setObject(paramCount++, param);
}
rowsAffected = stmt.executeUpdate();
conn.commit();
} catch (SQLException sqle) {
throw sqle;
//log error
} finally {
closeConnections(conn, stmt, null);
}
return rowsAffected;
}
There are some subtle differences. I do a commit, though autoCommit is the default.
Try like this:
DriverManager.getConnection("jdbc:mysql://localhost:3306/kot","root","root");