Can`t make insert in Oracle database from JSF Java web app - java

I have a JSF webapp and I encountered one problem. I want to take data that is from one table and is inserted in a datatable and insert it into a log table in the database.
I did the connection with the database but it doesn't show any errors and it doesn't insert anything.
I went in with the debugger from netbeans and the variables that I want to insert have values. I do not know where the problem is.
Here is the code:
package com.spv.raport;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleDataSource;
#Named(value = "dateBean")
#RequestScoped
public class DateBean {
private List<Date> dateList = new ArrayList<>();
public DateBean() throws ClassNotFoundException, SQLException {
String host = "jdbc:oracle:thin:#xxx:1521:xxx";
String user = "xxx";
String pass = "xxx";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement();
String sql = "select utilizator, tip_cerere, parametri, stare from
cereri where tip_cerere='D394' and utilizator='44192556' ";
ResultSet rs = stmt.executeQuery(sql);
String u = null;
String t = null;
String p = null;
String s = null;
String d = null;
while(rs.next()) {
u = rs.getString("utilizator");
t = rs.getString("tip_cerere");
p = rs.getString("parametri");
s = rs.getString("stare");
// d = rs.getString("creation_date");
dateList.add(new Date(u,t,p,s));
}
String host2 = "jdbc:oracle:thin:#xxx:xxx";
String user2 = "xxx";
String pass2 = "xxx";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con2 = DriverManager.getConnection(host2, user2, pass2);
Statement stmt2 = con2.createStatement();
String sql2 = "insert into SPV_RAPORT_LOG values ('serban', '123',
'parametru_test')";
stmt2.executeUpdate(sql);
} catch(SQLException se) {System.out.println(se);}
catch(Exception e) {System.out.println(e);}
}
public List<Date> getDateList() {
return dateList;
}
}
The database host and name and user and passwords are put intentionally with xxx to hide them.
I am a beginner and I do not have any idea why it doesn`t insert the test statement into the database table

Related

why do I get the error massage java.lang.RuntimeException: java.sql.SQLException: No database selected in my java code(linking with mysql database) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
package persistentie;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domein.Speler;
public class SpelerMapper {
private List<Speler> spelers = new ArrayList<>();
private List<Integer> scoreSpeler = new ArrayList<>();
private static final String UPDATE_SCORE = "insert into ID343589_g52.scoreSpeler(spelerNr,score) values(?,?)";
public SpelerMapper() {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement("SELECT * FROM ID343589_g52.speler");
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
String gebruikersnaam = rs.getString("gebruikersNaam");
String wachtwoord = rs.getString("wachtwoord");
spelers.add(new Speler(gebruikersnaam, wachtwoord));
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public boolean correcteGegevens(Speler nieuweSpeler) {
return spelers.contains(nieuweSpeler);
}
public List<Integer> geefscoreSpeler(String naam) {
scoreSpeler.clear();
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
int score = rs.getInt("score");
scoreSpeler.add(score);
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return scoreSpeler;
}
public void slaScoreOp(int score, String naam) {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
int id = 0;
while (rs.next()) {
id = rs.getInt("score");
}
PreparedStatement update = conn.prepareStatement(UPDATE_SCORE);
update.setInt(1, id);
update.setInt(2, score);
update.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
anything stupid I am doing here that is realy not how it working? I am really new to connecting a database with my java projects? the thing that I am trying to do in methode geefScoreSpeler() is getting the scores of an idividual player. and in methode slaScoreOp() I am trying to insert a new column in a table (also trying to get the id of the username via a table that innerjoins)
Hey there I made a user management system and this is my DAO(Databases connection class)
I have used prepared statement in this to see if it might help.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import com.ums.beans.ems.Employee;
public class EmployeeDao {
Connection connection;
Statement statement;
public EmployeeDao() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_1", "root", "apaar121");
}
public int saveEmployee(Employee employee) throws SQLException {
String query = "INSERT INTO user_1.employee ('name','dob','address','phone','email','education','designation','salary')VALUES (?,?,?,?,?,?,?,?);";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,employee.getName());
preparedStatement.setString(2,employee.getAddress());
preparedStatement.setString(3,employee.getDesignation());
preparedStatement.setString(4,employee.getDob());
preparedStatement.setString(5,employee.getEducation());
preparedStatement.setString(6,employee.getEmail());
preparedStatement.setString(7,employee.getPhone());
preparedStatement.setFloat(8,employee.getSalary());
return preparedStatement.executeUpdate();
}
}

Netbeans MySQL Connection - not to do with jbdc

I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.

Sybase jdbc4 not returning any results from sql query

I'm trying to run a query against a Sybase database. It seems like the connection is made successfully but when it hits rs.next() it fails to go to the first row in the results. It jumps down to the rs.Close().
I know for a fact that my query below works. I'm running it in a sql tool and it returns one record.
Please can someone tell me what I'm doing wrong?
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import com.sybase.jdbc4.jdbc.SybDataSource;
import com.sybase.jdbc4.jdbc.SybDriver;
public class test {
public static void main(String[] args) throws SQLException {
SybDriver sybDriver = null;
Connection conn = null;
Statement stmt = null;
String host = "123.12.34.56";
String url = "jdbc:sybase:Tds:"+host+":1300";
String username = "testuser";
String password ="password";
try{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select top 1 brand, model,color,serialnum from myTable order by newid()");
while(rs.next())
{
String one = rs.getString(1);
String two = rs.getString(2);
String three = rs.getString(3);
String four = rs.getString(4);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
}
}

Jtable how to display data from mysql in different Columns

I am trying to display data from the database in java using Jtable, yes I have achieved that but now the conflict is the surname and name they are displayed in one Column yet I would like them to be displayed in different columns . below is my code please help ..
import java.awt.Dimension;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ju {
private static Object request;
static JTable mysTable;
//constructor method
public static void main (String args []){
String [] columnNames = {"Name","Lastname","Id","Style"};
mysTable = new JTable(4,4);
mysTable.setBounds(20,10,300,300);
JFrame frame = new JFrame("King Musa Saloon Software");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(500,500);
frame.setResizable(false);
frame.setVisible(true);
frame.add(mysTable);
//frame.add(mysTable);
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loading success!");
String url = "jdbc:mysql://localhost:3306/saloon";
String name = "root";
String password = "";
try {
java.sql.Connection con = DriverManager.getConnection(url, name, password);
System.out.println("Connected.");
// pull data from the database
java.sql.Statement stmts = null;
String query = "select userid, username, name from saloonuser ";
stmts = con.createStatement();
ResultSet rs = stmts.executeQuery(query);
int li_row = 0;
while(rs.next()){
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
int userid = rs.getInt("userid");
String username = rs.getString("username");
String name1 = rs.getString("name");
System.out.println(name1);
li_row++;
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Take a look at your code here:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
It's writing in the same column, you should change it to:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,1);
Try and see if it work :)

selecting data from cassandar using cql

i am using cassandra-jdbc to perform the operation on data in cassandra but when i run this simple program i get exception.
this is my code:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.*;
import javax.sql.*;
public class Operations
{
public static void main(String[] args){
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/temp");
String qry = "select name FROM cql";
Statement smt = con.createStatement();
ResultSet resultSet = smt.executeQuery(qry);
System.out.println(resultSet);
while(resultSet.next())
{
System.out.println(resultSet);
}
}
catch(Exception e)
{
System.out.println(" : "+e.getMessage());
}
}
}
i got :cannot parse 'name' as hex bytes
Try:
import static org.apache.cassandra.utils.Hex.bytesToHex;
...
String name = bytesToHex("name".getBytes());
String qry = "select '" + name + "' FROM cql";

Categories