I had this working at one point, but changed the path along with some other fields and now I just cant seem to get it updating again. Here is the code:
public class DbUpdate{
ResultSet rs;
Statement st;
public void DbUpdate(){
Connect();
}
public void Connect(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\User\\ugt\\Desktop\\ResourcePlanningTool_DB.accdb");
st = con.createStatement();
st.executeUpdate("INSERT INTO AssignmentDetails (Name) VALUES('Bob Joll')");
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args){
DbUpdate x = new DbUpdate();
}
}
At the moment the project runs without errors, but it doesn't seem to actually update the table. Also the path name is correct.
The public void DbUpdate() isn't quite a constructor and wasn't called. I removed the void and also added a con.commit() after the executeUpdate and it worked.
Edit: The commit doesn't seem to be needed.
int retVal = st.executeUpdate("INSERT INTO AssignmentDetails (Name) VALUES('Bob Joll')");
System.out.println("Inserted: " + retVal);
//con.commit();
//con.close();
Related
So I'm currently working on a project that will be using a database but its my first time trying fiddling with it on java.
But I'm already seeing my first problem is how would i make one single file that handles connection while other files handles GET/ADD/UPDATE/DELETE (one for each table) what would properly be the best way on doing this ?
To not having to place connection values in each file and do the connection
I though about extending the connection class with the other classes but idk if its a great idea.
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
final String url = "jdbc:postgresql://localhost:5432/Database";
final String user = "dbuser";
final String password = "dbpass";
try(Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
What would be the best approach?
Maybe i'm wrong, but i think you need connection pool.
Try to find instruction here https://www.baeldung.com/java-connection-pooling
You could move the database connection related code to a utility class, and use the PreparedStatement class to precompile the SQL Query
public class doSomething {
Connection conn = null;
PreparedStatement pst = null;
public static void main(String [] args){
conn = DatabaseConnection.connect()
String qry = "Select * from table_name";
pst = (PreparedStatement) conn.prepareStatement(qry);
}
}
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.
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.
I'm trying to connect with MS-Access using java but When I Compile this code it gives me no error and compile fine but it doesn't show any result while the database has records in it, table name and field name are also correct, anyone can please help me that what I'm doing wrong in it.
import java.sql.*;
public class database{
Connection dbCon;
Statement statement;
ResultSet result;
public database(){
connect();
}
public void connect(){
try{
String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(Driver);
String Sdb = "jdbc:odbc:students";
dbCon = DriverManager.getConnection(Sdb);
statement = dbCon.createStatement();
String sqlQuery = "SELECT * FROM StudentInfo";
result = statement.executeQuery(sqlQuery);
while(result.next()) {
//String name = result.getString("Studentname");
System.out.println(result.getString("Studentname"));
}
}catch(Exception ex){
}
}
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
new database();
}
}
You are not getting error during execution of program because you are eating exception here:
catch(Exception ex){
}
You should try to print the exception trace to know what is going wrong.
catch(Exception ex){
ex.printStackTrace();
}
I have some issues with the conection between java application and mysql.
This is my file(this file work very well):
import java.sql.*;
import javax.swing.JFrame;
public class MysqlConnect{
public static void main(String[] args) throws SQLException {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "birthday";
String password = "123456";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Is possible "to separate" the main and mysql connection ??
My idea is something like that :I have the MysqlConnection file and another GUI file.
In the GUi file I have a button (ADD) and whenever I click this button some datas will be stored to database .My problem is that I don't know how run the query ,because I need the Statement variable ,Connection variable,etc..What I suppose to do ?To do the mysqlConnection and GUI in the same file ?Another idea of mine is to do an object of type MysqlConnection and work with that object.And here is the problem :If I remove the (public void main .....) i have an error at try and catch.
Sorry if my english is bad but I hope i make myself clear .
Thanks in advance .
What I understand from your question is that you want to make an application that shows data from a database in a GUI. Maybe you should look into an architecture like MVC (Model-View-Controller) where you have the model as an representation of the data in the database and having the view as a graphical representation of the model.
Since it didn't came to mind to apply a certain architecture, I would recommend you to look into that first, do a little bit of research and then implement your system. When looking into the MVC-architecture, I recommend you to start here. This is really the most easy example you could think of.
About your database connection: your setup looks good, though first of all, put it in a separate class and add query functionality to it. While implementing that part, this would come in handy. After that, you can let the Controller call the database to manipulate the Model on a button press, which will update the View (GUI) in your MVC-architecture.
So, do NOT put your database connection and your Main or GUI in the same class! This is a bad code style, violates the Single Responsibility Principle and will give you more trouble in future developing! Instead, use a proper architecture
If you want further help, always feel free to ask! I have recently studied this kind of stuff and made an application like this.
Hi RvanHeest thank you very much for your time.I try to do like that :
MysqlConnect.java
public class MysqlConnect{
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public String query="Select * From Person";
public Statement stmt;
public ResultSet rs;
public void crearedatabase(){
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
and in mine Gui class like that :
GUi file:
.................
................
MysqlConnect mysqlitem = new MysqlConnect();
mysqlitem.crearedatabase();
String query = "INSERT INTO persons("
+ "id"
+ "name"
+ "lastname"
+ "date) "
+ "VALUES(null,Maxim,Alexandru-Vasile,1990-12-28)";
try{
mysqlitem.rs=mysqlitem.stmt.executeQuery(query);
}
catch(Exception e1){
System.out.println("Eroare");
}
On the " mysqlitem.rs=mysqlitem.stmt.executeQuery(query);" I have an Exeption error and I don't know how to resolve..
Thank you very much again !!!
I ran in to the same issue.
I found the root cause to be that you are declaring the stmt variable twice.
Your code should look this like:
public class MysqlConnect{
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public String query="Select * From Person";
public Statement stmt;
public ResultSet rs;
public void crearedatabase(){
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Note the change to the line 18 "stmt = conn.createStatement();"
I wrote this code for create a separate dbconnection class on a separate java file and its working fine for me.
public class dbConnection{
public Connection getConnection()
{
String url = "jdbc:mysql://localhost:88/shop";
String username = "root";
String password = "";
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
con = DriverManager.getConnection(url, username, password);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
// USING THE ABOVE CONNECTION ON DIFF CLASS
-----------
Connection con=new dbConnection().getConnection();
------------
Credits to StackOverFlow...
public class LoadDriver {
public static void sqlDriver(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
and in your main class
try {
LoadDriver.sqlDriver(null);