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);
}
}
I have another class where a user a Book a resort, by only typing in the ID of the resort. Then a new JFrame opens(ConfirmBooking) where it displays the Name of the Resort and Price per night on labels. But I seem to be getting an error where I try to load the Resort name and price from the SQL database.
Error I get:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
public class ConfirmBooking extends javax.swing.JFrame
{
Connection conn = null;
Statement stat = null;
ResultSet res = null;
Booking B = new Booking();
public ConfirmBooking()
{
initComponents();
String sql = "SELECT RESORT_NAME, COST_PER_NIGHT_ZAR FROM LouwDataBase.Resorts WHERE ID = "+ 2;
try (PreparedStatement pstmt = conn.prepareStatement(sql))
{
try (ResultSet rs = pstmt.executeQuery())
{
if (rs.next())
{
String Name = rs.getString("RESORT_NAME");
double Price = rs.getDouble("COST_PER_NIGHT_ZAR");
String Rands = Double.toString(Price);
ResortName.setText(Name);
ResortPrice.setText("R"+Rands);
}
}
}
catch (SQLException ex)
{
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}
}
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
You have to initialize your connection to Database
https://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
public class DB
{
public static void main(.....)
{ String str="hello";
....
st.executeUpdate("insert into r2( col1) values(.....)"); // here r2 is the table in which i want to insert the "str" defined above.
}}
i want to insert this 'str' in the table r2 using the insert command.
WHAT DO I WRITE HERE? TO INSERT VALUE OF "str" PREVIOUSLY DEFINED , how to pass the parameter 'str' from outside such that it gets inserted into the table??
You will write it like this .. assuming column name in table r2 is col1
public class DB
{
public static void main(.....)
{ String str="hello";
.... // Obtain DB Connection here
PreparedStatement ps = connection.prepareStatement("insert into r2( col1) values(?)";
ps.setString(1,str);
ps.execute();
}
}
The safest way is to use a Prepared Statement.
Here is Oracle's very comprehensive tutorial on using Prepared Statements.
In your case (assuming the column you want to insert the value into is named "world") it would be done something like this:
String str="hello";
Connection connection = [...] // Set up connection
String queryString = "insert into r2 ('world') values(?)";
Statement statement = connection.prepareStatement(queryString);
statement.setString(1, str);
statement.executeUpdate();
// Add exception handling, clean-up
Try it and see if it helps.
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
PreparedStatement ps = conn.prepareStatement("insert into table_name( col1,col2,col3) values(?,?,?)";
ps.setString(1,str);
ps.setString(2,str);
ps.setString(3,str);
ps.execute();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
I have recently deployed a DB Instance on Amazon RDS and I am trying to get the hang of it. After following the instructions on the documentation I tried connecting to that DB Instance but for some reason my simple program which shows the server's version hangs on the connection.
Here is my code:
import java.sql.*;
public class AWSTest {
public static void main(String[] args) {
System.out.println(getVersion());
}
public static String getVersion() {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("Driver Error: " + e.getMessage());
return VERSION_NOT_FOUND;
}
System.out.println(CONNECTING_MESSAGE);
try (Connection con = DriverManager.getConnection(DB_URL,
USER,
PASS);
Statement stmt = con.createStatement();) {
System.out.println("Getting server version...");
try (ResultSet rs = stmt.executeQuery(VERSION_QUERY);) {
rs.next();
return rs.getString(1);
}
} catch (SQLException se) {
System.out.println("SQL Error: " + se.getErrorCode() + " "
+ se.getMessage());
return VERSION_NOT_FOUND;
}
}
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://**************.*******."
+ "*******.rds.amazonaws.com:3306";
private static final String VERSION_QUERY = "Select VERSION()";
static final String USER = "*******";
static final String PASS = "*******";
private static final String VERSION_NOT_FOUND = "Version was not found";
public static final String GETTING_DRIVER_MESSAGE = "Getting driver...";
public static final String CONNECTING_MESSAGE = "Connecting to server...";
}
My program hangs at the line Connection con = DriverManager.getConnection(DB_URL, USER, PASS); and my main problem is that it does not even throw an exception, it just stays there.
USER, PASS and DB_URL are definitely correct.
It sounds like your ip/port is getting blocked/dropped. That's typically the case when a connection does nothing (as opposed to getting refused or failed login). Make sure your Security Group is set up properly. http://aws.amazon.com/rds/faqs/#31
I am new to programming and i am trying to make an small Java swing application using netbeans IDE and i have designed the Form and created an table too i used the following code to insert data into database from the form but i am getting many errors please help me to correct this code:
import java.sql.*;
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
static final String USER="root";
static final String PASS="toor";
Connection conn = null;
Statement stmt = null;
static final String d_unit=jTextField2.getText();
static final String d_name=jTextField3.getText();
static final String d_dob=jDateChooser2.getText();
//static final String d_gender="gender";
static final String d_age=jTextField4.getText();
static final String d_doorno=jTextField5.getText();
static final String d_street=jTextField6.getText();
static final String d_vc=jTextField7.getText();
static final String d_district=jTextField8.getText();
static final String d_pin=jTextField9.getText();
static final String d_phone=jTextField10.getText();
static final String d_mail=jTextField11.getText();
static final String d_occupations=jTextField12.getText();
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) values('"+d_unit+"','"+d_name+"','"+d_dob+"','"+d_age+"','"+d_doorno+"','"+d_street+"','"+d_vc+"','"+d_district+"','"+d_pin+"','"+d_phone+"','"+d_mail+"','"+d_occupations+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e)
{ }
}
You may not use the final String because, then you can't modify these Strings, and the other code is correct, but i think you can use the ? in the line:
String sql="INSERT INTO ´donors´ (unit,name) VALUES (?,?)";
//put the rest of the sentence
try {
PreparedStatement pdt = cn.prepareStatement(sql);
pdt.setString(1, jTextField2.getText();
pdt.setString(2, jTextField3.getText();
//put the rest of the code
int n1=pdt.executeUpdate();
if(n1>0)
{
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
}catch (SQLException ex) { }
Well, that's the largest way, but the most correct. I hope this helps.
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode = txtItemCode.getText();
String itemName = txtItemName.getText();
String unitPrice = txtUnitPrice.getText();
String qty = txtQty.getText();
String query = "insert into items values ('"+itemCode+"','"+itemName+"','"+unitPrice+"','"+qty+"')";
System.out.println(query);
try {
Connection c = DBClass.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Saved");
} catch (Exception e) {
e.printStackTrace();
}
// DBClass
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author Nadun
*/
public class DBClass {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stock", "root", "123");
}
return connection;
}
}
Everything looks alright. Maybe the trouble is on your mysql database?
Check the data type of your row in mysql, if your data type in the current row is "int", then it should be like this
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (name, age) values('"+d_name+"',,'"+Integer.valueOf(d_age.getText().toString())+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e){ }
}
You should be careful with data types. If your mysql row is int type then in your java you should give it int time as well.
I guess your data type of "name" row is text that use string, and your data type of "age" row is int?
I check your code is giving a string value from your java to your int mysql row. that's the error.
So you should convert the string to the int first
Integer.valueOf(d_age.getText().toString());
try proceeding like this for simplicity and less error-prone
String sql = "INSERT INTO donors(unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
stmt.executeUpdate(sql);