This question already has answers here:
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Error [duplicate]
(2 answers)
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
This is my simple code to test connectivity with MySQL :
import java.sql.*;
import java.util.*;
public class PreparedStatementTest {
public static void main(String[] args) throws Exception {
String[] str = {"ram", "shyam", "radhe", "lakhan"};
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:shubh", "sa", "shubham");
PreparedStatement ps = con.prepareStatement("insert into shubham_table values(?,?)");
for (int i = 0; i < 4; i++) {
ps.setInt(1, i);
ps.setString(2, str[i]);
ps.executeUpdate();
}
PreparedStatement prs = con.prepareStatement("select *from shubham_table where id=?");
for (int i = 0; i < 4; i++) {
prs.setInt(1, i);
ResultSet rs = prs.executeQuery();
while (rs.next()) {
System.out.print("id = " + rs.getInt(1));
System.out.println("name = " + rs.getString(2));
}
}
rs.close();
prs.close();
ps.close();
con.close();
}
}
This code is working properly and updating my already existing table in database but when I try to create a connection in my web app on Apache it throws ClassNotFoundException. The source code in my application is
import javax.servlet.*;
import java.io.*;
import java.sql.*;
import java.util.*;
public class RegFormServlet implements Servlet {
public void init(ServletConfig sc) throws ServletException {
System.out.println("created");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
System.out.println("before con mysql");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:shubh", "sa", "shubham");
String name = req.getParameter("name");
String email = req.getParameter("email");
String address = req.getParameter("address");
Statement st = con.createStatement();
String ddl =
"create table shubham_table3 (name varchar(30),e-mail
varchar(20)
,address varchar
(100))";
st.execute(ddl);
PreparedStatement ps = con.prepareStatement(
"insert into shubham_table
values( ?, ?, ?)
");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, address);
PrintWriter out = res.getWriter();
out.println("You Are Registered Successfully yeah!!!!");
st.close();
ps.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
How can I fix this?
You are using Type1 jdbc driver to connect to Mysql database. Please check Tomcat and its jdk version. From Jdk8 onwards Type1 driver is not allowed to use.
Alternatively you can use Mysql Type4 driver to do operation. Here is link
Once downloaded mysql connector driver add it to /WEB-INF/lib folder.
Hopefully It should solve issue.
Related
We have an older application that can't failover when one node of our Oracle RAC goes down. It seems it uses an older version of org.apache.commons.dbcp.BasicDataSource. I can make this work when I use UCP from Oracle but when I use the apache version the app dies as soon as I shut down the node of the RAC it is connected to. Am I missing something or does it not work with Apache DBCP? Thanks
Here is my code.
import org.apache.commons.dbcp.BasicDataSource;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BasicDB{
final static String DB_URL ="jdbc:oracle:thin:user/password#pdb_tac";
final static String driverClassName = "oracle.jdbc.replay.OracleDataSourceImpl";
private void pressAnyKeyToContinue()
{
System.out.print("Press any key to continue...");
try { System.in.read(); }
catch(Exception e) { e.printStackTrace(); }
}
public String getInstanceName(Connection conn) throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("select instance_name from v$instance");
String r = new String();
for(ResultSet result = pstmt.executeQuery(); result.next(); r = result.getString("instance_name")) {
}
pstmt.close();
return r;
}
private void doTx(Connection c, int numValue) throws SQLException {
String updsql = "UPDATE test SET v=UPPER(v) WHERE id=?";
PreparedStatement pstmt = null;
pstmt = c.prepareStatement(updsql);
c.setAutoCommit(false);
for(int i = 0; i < numValue; ++i) {
pstmt.setInt(1, i);
pstmt.executeUpdate();
}
c.commit();
pstmt.close();
}
public static void main(String[] args) throws SQLException {
Connection conn = null;
int numValue = 5000;
;
try {
BasicDataSource bods = new BasicDataSource();
bods.setUrl(DB_URL);
bods.setDriverClassName(driverClassName);
bods.setDefaultAutoCommit(false);
BasicDB self = new BasicDB();
conn = bods.getConnection();
String var10001 = self.getInstanceName(conn);
var10000.println("Instance Name = " + var10001);
System.out.println("Performing transactions");
self.pressAnyKeyToContinue();
self.doTx(conn, numValue);
var10001 = self.getInstanceName(conn);
var10000.println("Instance Name = " + var10001);
} catch (Exception var8) {
var8.printStackTrace();
}
}
}
Ok, so it has to do with using the DataSource instead of the DataDriver class. I have run into another error so will create a new question for that.
I am working in command prompt this is my code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnf) {
System.out.println("Driver could not be loaded: " + cnf);
}
}
public static void main(String[] args)
{
String connectionUrl = "jdbc:mysql://localhost:3306/mysql";
String dbUser = "root";
String dbPwd = "admin";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM exptable";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
// INSERT A RECORD
stmt.executeUpdate("INSERT INTO exptable (name) VALUES (\"TINU K\")");
// SELECT ALL RECORDS FROM EXPTABLE
rs = stmt.executeQuery(queryString);
System.out.println("ID \tNAME");
System.out.println("============");
while (rs.next()) {
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}
i am getting error like
java.lang.ClassNotFoundException and java.sql.SQLException
so may i know what mistake have i made
You might have missed the classpath in your java command. While executing from command prompt you must mention the class path along with your command.
java -cp
ex:
java -cp /home/test/jars:/home/test/src com.test.Lab
While executing update by jdbc on Oracle dbms, my program hangs. I think it is waiting for another process/user to release lock on the rows or table that I am trying to update. So what are the possible causes for this problem and how can I solve it?
I am making calls to the dbms through jdbc as show here:
public static void updateEmployee(String name,int id) throws ClassNotFoundException
{
Connection con=null;
PreparedStatement st=null;
String driver= "oracle.jdbc.driver.OracleDriver";
String username="someuser";
String password="pwd";
String url="jdbc:oracle:thin:#hostname:1521:ORAJAVADB";
Class.forName(driver);
try
{
con=DriverManager.getConnection(url,username,password);
st=con.prepareStatement("update employee set employeeName=? where
employeeId = ? ");
st.setString(1,name);
st.setInt(2,id);
st.executeUpdate();
st.close();
con.close();
}
catch(SQLException ex)
{
}
}
I made this code for update function using java with oracle database. I hope it will help you. Good Luck
package updatemethod;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.pool.OracleDataSource;
public class UpdateMethod {
public static String url = "jdbc:oracle:thin:#mohammed:1521:XE";
public static String user = "md";
public static String password = "md";
public static String query;
public static Connection conn;
public static Statement smt = null;
// CREATE DATABASE CONNECTION
public static void getDBConnection() throws SQLException{
OracleDataSource ds;
ds = new OracleDataSource();
ds.setURL(url);
conn = ds.getConnection(user, password);
System.out.println("DataBase Accessed!");
}
public static void updateEmployee(String nID, String newFirst, String newLast, String newJob)throws SQLException{
try{
smt = conn.createStatement();
smt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = smt.executeQuery("SELECT ID, FIRSTNAME, LASTNAME, JOB FROM MD.EMPLOYEE1");
while(uprs.next()){
int newID = Integer.parseInt(nID);
uprs.updateInt("ID", newID);
uprs.updateString("FIRSTNAME", newFirst);
uprs.updateString("LASTNAME", newLast);
uprs.updateString("JOB", newJob);
uprs.updateRow();
System.out.println("DataBase Updated\n");
System.out.println("ID " + newID + " " + "FIRSTNAME " + newFirst + " " + "LASTNAME " + newLast + " " + "JOB " + newJob);
}
}
catch(SQLException er){
System.out.println(er);
}
}
public static void main(String[] args) throws SQLException {
// CREATE CONNECTION BY CALLING getDBConnection();
getDBConnection();
// NOW, CALL OUR updateEmployee(String,String,String,String) FUNCTION
updateEmployee("123", "mohammed", "Jamal", "Computer Technique Engineer");
}
}
Hi I a have MySql installed with Netbeans and have been trying to use Java with MySQL, however I am running into an issue when I run it. My database is called "test" and my table is "task". The two columns I have are: "id", and "task" (and I realized that naming a variable the same as the table probably is not a good idea). I also have a side question in the code area asking what it does. This is the error:
run:
May 22, 2015 11:52:25 PM databasetest.DatabaseTest main
SEVERE: Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6986)
at databasetest.DatabaseTest.main(DatabaseTest.java:43)
BUILD SUCCESSFUL (total time: 41 seconds)
This is my code:
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "cinder";
try {
String author = "Trygve Gulbranssen";
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
//^^ what is VERSION? What is this supposed to be doing?
for (int i=1; i<=1000; i++) {
String query;
query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
SELECT VERSION() is meant to tell you your MySQL version. First, print the result of the SELECT then run your other queries. Running intermediate insert queries with the Statement implicitly closes the ResultSet, hence your error. Move
if (rs.next()) {
System.out.println(rs.getString(1));
}
before you run
for (int i=1; i<=1000; i++) {
// String query;
String query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}
Hey for some reason my sql statement will not work, im trying to delete a product by its id but it just wont happen, any suggestion? the id is an integer and i think its not working because my input type is text and i have it stored as String n.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Admin extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("productid");
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = " + n +"";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setString(1, n);
int i = stmt.executeUpdate();
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
} catch (ClassNotFoundException | SQLException ey) {
System.out.println(ey);
}
out.close();
}
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = ?";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setInt(1, Integer.parseInt(n));
int i = stmt.executeUpdate();
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
}
make above 2 changes.
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = " + n +"";
Statement stmt=con.createStatement();
int i = stmt.executeUpdate(query);
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
} catch (ClassNotFoundException | SQLException ey) {
System.out.println(ey);
}
please try this code,it should works fine
Problem in your code is that product id is Integer type in database but u have set it as String
in your code stmt.setString(1, n); it should be changed to stmt.setInt(1, n) and query format should be like this String query = "delete from product where id = ?";.here is the code for deleting product from database using productId.
String query = "delete from product where id = ?";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setString(1, n);
just replace this code it will work...
Found two issues in your code:
You didn't properly set the parameters in the PreparedStatement call.
You didn't close the statement and connection.
Try this:
public class Admin extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("productid");
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = ?";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setString(1, n);
int i = stmt.executeUpdate();
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
}
catch (ClassNotFoundException | SQLException ey) {
System.out.println(ey);
}
finally{
stmt.close();
con.close();
}
}
Since the field is a text type, it needs surrounding quotes - that's why that didnt work. Calling setString didnt have any effect as there's no placeholder to accept the id value.
Solution: Add a PreparedStatement placeholder:
String query = "delete from product where id = ?";
This approach protects against SQL Injection attacks whereas String concatenation does not.