I have main page index.jsp. from jsp page requset has been sent to database.But database connection is not happening.Its not giving any error and its giving blank page.Even I have added mysql connector.jar to library file.am using tomcatserver. Can anybody please help me what is the problem.Here is the complete code
disply.java
public class MyDb {
Connection con;
public Connection getcon() {
try {
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "adminuser");
} catch (ClassNotFoundException ex) {
Logger.getLogger(MyDb.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(MyDb.class.getName()).log(Level.SEVERE, null, ex);
}
return con;
}
}
You have to assign the Connection Object to the connection returned from the DriverManager
Connection con = null;
....
con = DriverManager.getConnection("jdbc:mysql......
Related
I really need your help guys .... I am trying to make a java program connects to mysql database, and I used to connect with localhost by xampp and its working fine with this code ...
public class myConnection {
public static Connection getconnection(){
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test?serverTimezone=Turkey","root","");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return con;
}
}
but now I just bought an online server and made a new datebase Inside it but I have no Idea how to connect my program with it I tried a lot and I searched for many hours but I couldnt find anything about that... this is my database
and this is the code I am trying to use but I always get Communications link failure ..
public static Connection getconnection(){
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://mysql.bravehost.com/afkodb_3483514","username","password");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return con;
}
So I have setup my code like so
public static Connection getConnection() {
try {
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=HRDB;
String user = "sa";
String pass = "r";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(dbURL, user, pass);
return conn;
} catch (ClassNotFoundException c) {
return null;
} catch (SQLException s) {
System.out.println(s.toString());
return null;
}
}
However, when I try to connect to the database I get the following exceptions.
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "java.lang.RuntimeException: Could not generate DH keypair".
Driver Not Foundjava.lang.ClassNotFoundException: com.mysql.jdbc.driver
I want to make connection between my java web application and mysql database through XAMP.
I also have added external jar file which is mysql-connector-java-6.0.2.jar but still i am getting this error.
I have done this code.
public static void main(String[] args)
{
try {
Class.forName("com.mysql.jdbc.driver");
System.out.println("Driver has been found..");
} catch (ClassNotFoundException ex) {
System.out.println("Driver Not Found"+ex);
}
String url="jdbc:mysql://localhost/hms";
String user="root";
String password="";
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
System.out.println("Driver is successfully loaded.");
} catch (SQLException ex) {
System.out.println("Something is not good.");
}
}
Class names in Java are case-sensitive. You need to capitalize the "D" in "driver":
Class.forName("com.mysql.jdbc.Driver");
// Here ----------------------^
You should write this because because java is Case-Sensitive
public static void main(String[] args)
{
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver has been found..");
} catch (ClassNotFoundException ex) {
System.out.println("Driver Not Found"+ex);
}
String url="jdbc:mysql://localhost/hms";
String user="root";
String password="";
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
System.out.println("Driver is successfully loaded.");
} catch (SQLException ex) {
System.out.println("Something is not good.");
}
}
I'm developping a RESTful API with Jersey and MySQL.
I'm actually using the JDBC driver to connect to the database and I create a new connection everytime I want to acess it. As it clearly is a memory leakage, I started to implement the ServletContextClassclass but I don't know how to call the method when I need to get the result of a SQL query.
Here is how I did it wrong:
DbConnection.java
public class DbConnection {
public Connection getConnection() throws Exception {
try {
String connectionURL = "jdbc:mysql://root:port/path";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
return connection;
}
catch (SQLException e) {
throw e;
}
}
}
DbData.java
public ArrayList<Product> getAllProducts(Connection connection) throws Exception {
ArrayList<Product> productList = new ArrayList<Product>();
try {
PreparedStatement ps = connection.prepareStatement("SELECT id, name FROM product");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
productList.add(product);
}
return productList;
} catch (Exception e) {
throw e;
}
}
Resource.java
#GET
#Path("task/{taskId}")
#Consumes(MediaType.APPLICATION_JSON)
public Response getInfos(#PathParam("taskId") int taskId) throws Exception {
try {
DbConnection database= new DbConnection();
Connection connection = database.getConnection();
Task task = new Task();
DbData dbData = new DbData();
task = dbData.getTask(connection, taskId);
return Response.status(200).entity(task).build();
} catch (Exception e) {
throw e;
}
}
Here is where I ended up trying to implement the new class:
ServletContextClass.java
public class ServletContextClass implements ServletContextListener {
public Connection getConnection() throws Exception {
try {
String connectionURL = "jdbc:mysql://root:port/path";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
return connection;
} catch (SQLException e) {
throw e;
}
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
DbConnection database = new DbConnection();
try {
Connection connection = database.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
//con.close ();
}
}
But problem is, I don't know what to do next. Any help? Thanks
You need to set the Connection variable as an attribute of the ServletContext. Also, I would recommend using connection as a static class variable so you can close it in the contextDestroyed method.
You can retrieve the connection attribute in any of your servlets later on for doing your DB operations.
public class ServletContextClass implements ServletContextListener {
public static Connection connection;
public Connection getConnection(){
try {
String connectionURL = "jdbc:mysql://root:port/path";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
} catch (SQLException e) {
// Do something
}
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
getConnection();
arg0.getServletContext().setAttribute("connection", connection);
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
try{
if(connection != null){
connection.close();
}
}catch(SQLException se){
// Do something
}
}
}
Finally access your connection attribute inside your Servlet (Resource). Make sure you pass #Context ServletContext to your Response method so you can access your context attributes.
#GET
#Path("task/{taskId}")
#Consumes(MediaType.APPLICATION_JSON)
public Response getInfos(#PathParam("taskId") int taskId, #Context ServletContext context) throws Exception {
try {
Connection connection = (Connection) context.getAttribute("connection");
Task task = new Task();
DbData dbData = new DbData();
task = dbData.getTask(connection, taskId);
return Response.status(200).entity(task).build();
} catch (Exception e) {
throw e;
}
}
Now that we have solved your current issue, we need to know what can go wrong with this approach.
Firstly, you are only creating one connection object which will be used everywhere. Imagine multiple users simultaneously accessing your API, the single connection will be shared among all of them which will slow down your response time.
Secondly, your connection to DB will die after sitting idle for a while (unless you configure MySql server not to kill idle connections which is not a good idea), and when you try to access it, you will get SQLExceptions thrown all over. This can be solved inside your servlet, you can check if your connection is dead, create it again, and then update the context attribute.
The best way to go about your Mysql Connection Pool will be to use a JNDI resource. You can create a pool of connections which will be managed by your servlet container. You can configure the pool to recreate connections if they go dead after sitting idle. If you are using Tomcat as your Servlet Container, you can check this short tutorial to get started with understanding the JNDI connection pool.
I am using the GWT(Google Web Tool-Kit) version 2.5.1. I am already done for develop sample application to display that username and password. But i am not identifying how to insert that values into MySQL database table by using JDBC of Hiberante. Any body know's that please send me complete code.
This is my mail-id:
subbareddyroyal#gmail.com
thanks & regards
Subbareddy.N
GWT is NOT a java application environment. It compiles to javascript. You must send your data to a java server running in a full JVM.
Here above i am posting the question.My self i a finding the answer to insert values into my sql database by using the jdbc, GWT,and HTML.
Here i am posting that what i am changing in my application.
you add the below insert in you impl class under the server folder in gwt application.
public void insert(String name) throws CommunicationsException {
try {
System.out.println("Before loading the driver class");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("after loading the driver ");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/gwt", "root", "root");
System.out.println("after creating the connection");
PreparedStatement ps = con
.prepareStatement("insert into gwt_user(userName)values(?)");
System.out.println("after loading the query");
ps.setString(1, name);
int i = ps.executeUpdate();
if (i < 0) {
return;
}
} catch (SQLException e) {
System.out.println(e);
}
}
after that you can add the below try catch block in ur greetserver(optional Name) method under the impl class.
try {
insert(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
then remaining all files are same.No need to change any file in your application