Moving jdbc connection to property files in JSP - java

I am bit new to JSP and JDBC, I want to know how to move a JDBC connection like below to a property file for example to test.properties
Class.forName("oracle.jdbc.driver.OracleDriver");
//Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#nyvm0467.ptc.un.org:1521:EIDMSUAT", "DBO_EIDMSUAT", "NewPassDBO_EIDMSUAT");
Connection conn = DriverManager.getConnection("jdbc:", "ROD", "DMSP");
Statement statement = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY );
String queryString = "select area from helparea order by area";
ResultSet rs = statement.executeQuery(queryString);

One of the possibilities is as follows. correct me if I am wrong
ResourceBundle resource = ResourceBundle.getBundle("C:\\Users\\S.Mandava\\workspace2\\Contactus\\src\\OIMConnection");
String name=resource.getString("dbname");
String surname=resource.getString("dbpassword");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn2 = DriverManager.getConnection("jdbc:oracle:thin:#eidms-db-003.un.org:1521:EIDPMDM", resource.getString("dbname"), resource.getString("dbpassword"));
Statement statement2 = conn2.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY );
String queryString2 = "select area from helparea order by area";
ResultSet rs2 = statement2.executeQuery(queryString2);

Related

MySql not Connecting to Java

So this is my connection statements:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/usersdb";
String username = "root";
String password = "blasphemy3k";
Connection con = DriverManager.getConnection(url, username, password);
Statement st = (Statement) con.createStatement();
String sql = "select *from *students ";
ResultSet rs = ((java.sql.Statement) st).executeQuery(sql);
while(rs.next()) {
String id = String.valueOf(rs.getInt("id"));
String name = rs.getString(rs.getInt("name"));
String tbData[] = {id,name};
DefaultTableModel tblModel = (DefaultTableModel)jTable1.getModel();
tblModel.addRow(tbData);
}
When I run this code the compiler this message is shown also the jTable1 doesnt show any data from students table from usersdb
class com.mysql.cj.jdbc.StatementImpl cannot be cast to class
com.mysql.cj.xdevapi.Statement (com.mysql.cj.jdbc.StatementImpl and
com.mysql.cj.xdevapi.Statement are in module mysql.connector.java#8.0.29 of loader 'app')
Can you post imports of this java file?
Seems you import a wrong Statement class whose full name is com.mysql.cj.xdevapi.Statement, the right one should be java.sql.Statement.
I do not know which version of mysql-connetor-j you are using, this is what I found with version 8.0. StatementImpl implements JdbcStatement, and JdbcStatement implements java.sql.Statement (rather than com.mysql.cj.xdevapi.Statement, shows in the figures below).
So if you want to cast StatementImpl to Statement, this should work:
java.sql.Statement st = (java.sql.Statement) con.createStatement();
StatementImpl code
JdbcStatement code

MySQL Java prepared statement Syntax error

I need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.
I have read something about typing the question mark like \'?'// but I am not sure about the exact format.
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = con.createStatement();
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
ResultSet rs = stmt.executeQuery(sql);
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!
You are executing the query using a normal java.sql.Statement, not using a java.sql.PreparedStatement. This won't work because a normal Statement does not support parameterized queries. So, remove the creation and execution of the Statement, and make sure you execute the statement using the PreparedStatement:
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement preparedStmt = con.prepareStatement(sql)) {
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
try (ResultSet rs = preparedStmt.executeQuery()) {
// process result set
}
}
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.

How to write prepareStatement in Java

i want to use getParameter to get in Strings and ints and put them in a database using prepareStatement and SQL. It gives me errors with setString and setInt.
try {
String id = request.getParameter("clientid");
String cname = request.getParameter("clientname");
String address = request.getParameter("address");
String phonemodel= request.getParameter("phonemodel");
String imei = request.getParameter("imei");
String problem = request.getParameter("problem");
String date2 = request.getParameter("date");
String comments1= request.getParameter("comments");
int clientid = Integer.parseInt(id);
int imeino = Integer.parseInt(imei);
// int date1 = Integer.parseInt(date2);
Statement pstmt;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app" , "app");
pstmt=con.prepareStatement("Insert into movilapp(id,clientname,address,modle,imei,problem,date,comments) values(?,?,?,?,?,?,?,?)");
pstmt.setInt(1,clientid);
pstmt.setString(2,cname );
pstmt.setString(3,address);
pstmt.setString(4,phonemodel);
pstmt.setInt(5,imeino);
pstmt.setString(6,problem);
pstmt.setString(7, comments1);
pstmt.executeUpdate();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
You called con.prepareStatement to get a PreparedStatement, but then you assigned it to a variable of type Statement, so Java doesn't know that there is a PreparedStatement-specific method setString.
Assign it to an actual PreparedStatement variable, by changing the declaration type of pstmt from
Statement pstmt;
to
PreparedStatement pstmt;
*IF Use Statement Then its syntax is *
Statement stmt = null;
stmt = conn.createStatement( );
String sql = "UPDATE Employees set age=30 WHERE id=103";
stmt.executeUpdate(sql);
And for PreparedStatement it is
PreparedStatement pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
psmt.setInt(1,30);
psmt.setInt(2,1003);
psmt.executeUpdate(SQL);
So change Statement pstmt; to PreparedStatement pstmt = null; And it will work.

No Database selected when retrieving from mysql website

I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(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...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);

Java / database query : Retrieving multiple items

I have code to retrieve a database item and it displays that in a mobile application using J2ME. I also use JSP for this so that my mobile app can get information from this.
I want to know how I can retrieve multiple items??
JavaBean:
public String doQuery() throws ClassNotFoundException, SQLException {
//register driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//establish connection
Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/a1electric?user=root&password=raam030");
//Create a Statement object from the Connection
Statement stmt = Conn.createStatement();
String sql = "SELECT JobID FROM employee WHERE employeeID=" +this.jobID;
ResultSet rs = stmt.executeQuery(sql);
String rt = "";
rs.next();
rt = rs.getString("JobID");
Conn.close();
return rt;
}
JSP Page:
<jsp:useBean id="bean0" scope="session" class="data.queryBean"/>
<jsp:setProperty name="bean0" property="jobID" param="jobID"/>
<%= bean0.doQuery() %>
I would like to retrieve all the job IDs for this employee ID and display it.
If there are multiple JobIDs for a given EmployeeID, then your result set has all those items and you should browse through the resultset:
String sql = "SELECT JobID FROM employee WHERE employeeID=" +this.jobID;
ResultSet rs = stmt.executeQuery(sql);
List<String> jobIds = new ArrayList<String>();
while (rs.next()) {
jobIds.add(rs.getString("JobID"));
}
On a related note, you should
try to use a connection pool (apache DBCP), instead of registering the driver and connecting to the DB everytime.
use PreparedStatement to avoid potential SQL injection attacks:
PreparedStatement stmt = con.prepareStatement(
"SELECT JobID FROM employee WHERE employeeID= ?");
stmt.setInt(1, this.jobID);
ResultSet rs = stmt.executeQuery();

Categories

Resources