Can't display SQL data on labels - java

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

Related

statement.executeQuery) not working in NetBeans java

I am trying to output the first column (nameID) of my table (StudentInfo) in my database. But the statement.executeQuery is not working and ResultSet.next() is false.
Java NetBeans program
Calls sqlite database
Uses "jdbc:sqlite:ProjectWeekDB.sqlite" as url
private static Connection connection = null;
private static PreparedStatement stmt = null;
private static Statement statement = null;
private static ResultSet results = null;
public static void createNewDatabase() {
String sqlData = "SELECT * FROM StudentInfo";
String url;
try {
connection = DriverManager.getConnection(url);
if (connection != null) {
statement = connection.createStatement();
stmt = connection.prepareStatement(sqlData);
statement.executeUpdate(sqlData);
results = statement.executeQuery(sqlData);
while (results.next()) {
print(results.getInt("nameID"));
}
stmt.close();
results.close();
}
} catch (SQLException e) {
print(e.getMessage());
}
}
public static void main(String[] args) {
createNewDatabase();
}
It just prints out BUILD successful without actually displaying the first column in the database.

No suitable driver found for jdbc:mysql//localhost/sakila

I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";

Why i can not connect to mysql db using java

I have used jdbc driver before.But for this piece of program i can't connect to the db.This doesn't throw any exception or anything. Just won't connect. I couldn't find a solution online either.Below is the code i tried to run :( Please help in solving this. Thank you in advance :)
public class HeapMySql<T extends Comparable<T>> implements HeapInterface {
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Heap";
static final String USERNAME = "root";
static final String PASSWORD = "";
private int size = 0 ;
String sql;
static Statement stmt = null;
static Connection conn = null;
static ResultSet rs = null;
public void HeapMySql(){
try
{
sql = "CREATE TABLE testHeap (index integer, value integer);";
stmt.executeUpdate(sql);
System.out.println("Done");
}catch(Exception e){
}
}
public static void main(String [] arg){
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database..."); //lets create a table in our database
stmt = conn.createStatement();
HeapMySql test1 = new HeapMySql<>();
}catch(ClassNotFoundException | SQLException ex){
}finally{
}
A constructor does not have a return type: docs
Remove void from public void HeapMySql() and it will do the work.
Also as said in comments, you should print the stacktrace in your catch blocks. This makes it easy to understand the exception and resolve the problem.

getting values in jtable upon seletio on jcombox

1.i have a jcombobox which is getting the value from database ,
2. upon the selection on the value i want to display that particular row in the jtable ,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Object obj = jComboBox1.getSelectedItem();
String tmpr = obj.toString();
Rtable rObj = new Rtable();
rObj.setUserName(tmpr);
}
private void Update_table(){
String Sql = "SELECT * FROM r_db1.dbo.user_names " + jComboBox1.getSelectedItem()
I am getting a error like "UnsupportedOperationException("Not supported yet.")"
Try this
use loadcombo() method to load ur jcombobox.
void loadcombo()
{
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
//userID = "Admin";
password = "***";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop","system","manager");
st=con.createStatement();
rs= st.executeQuery("select distinct(Name) from Table");
while(rs.next())
{
jComboBox.addItem(rs.getString(1));
}
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
use jcombobx actionlistener to load data into jtable.
jComboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";";
//sql = "SELECT * FROM tblUserProfile";
Object name=jComboBox.getSelectedItem();
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop","system","manager");
st=con.createStatement();
model.setRowCount(0);
data = getvalue(name);
JTable table1=new JTable(data,header);
for(int i=0;i<table1.getRowCount();i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};model.addRow(d);
}
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
public Vector getvalue(Object name)throws Exception
{
Vector<Vector<String>> vector = new Vector<Vector<String>>();
Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from Table where Name='"+name+"'");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> c = new Vector<String>();
c.add(rs.getString(4));
c.add(rs.getString(5));
c.add(rs.getString(6));
vector.add(c);
}
/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();
return vector;
}
});

How to insert data into database from the main file?

I've got 2 file in my java project : MysqlConnect and Main .
I want to run query from Main class.It's possible?
This is MysqlConnect file:
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 Statement stmt;
public String query = "";
public int 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("Baza de date nu a fost creata");
}
}
public void executeSql() {
try {
rs = stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println("Mysql Error");
}
}
}
And this is the Main file:
public class Main {
public static void main(String[] args) throws SQLException
{
MysqlConnect sqlconnect = new MysqlConnect();
sqlconnect.crearedatabase();
sqlconnect.query="INSERT INTO `jdbctutorial`.`persons` (`id`, `nume`, `prenume`, `data`) VALUES (NULL, 'xxxx', 'xxxx', '1990-12-12');";
sqlconnect.executeSql();
}
}
The error(Exception) is on the MysqConnection at the try/catch
rs = stmt.executeUpdate(query);
You assign statement object to a local variable named stmt instead of the object field with the same name.
Replace this
Statement stmt = conn.createStatement();
With this:
this.stmt = conn.createStatement();
this is not necessary here, but it's a good practice to have it there.

Categories