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.
I have recently deployed a DB Instance on Amazon RDS and I am trying to get the hang of it. After following the instructions on the documentation I tried connecting to that DB Instance but for some reason my simple program which shows the server's version hangs on the connection.
Here is my code:
import java.sql.*;
public class AWSTest {
public static void main(String[] args) {
System.out.println(getVersion());
}
public static String getVersion() {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("Driver Error: " + e.getMessage());
return VERSION_NOT_FOUND;
}
System.out.println(CONNECTING_MESSAGE);
try (Connection con = DriverManager.getConnection(DB_URL,
USER,
PASS);
Statement stmt = con.createStatement();) {
System.out.println("Getting server version...");
try (ResultSet rs = stmt.executeQuery(VERSION_QUERY);) {
rs.next();
return rs.getString(1);
}
} catch (SQLException se) {
System.out.println("SQL Error: " + se.getErrorCode() + " "
+ se.getMessage());
return VERSION_NOT_FOUND;
}
}
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://**************.*******."
+ "*******.rds.amazonaws.com:3306";
private static final String VERSION_QUERY = "Select VERSION()";
static final String USER = "*******";
static final String PASS = "*******";
private static final String VERSION_NOT_FOUND = "Version was not found";
public static final String GETTING_DRIVER_MESSAGE = "Getting driver...";
public static final String CONNECTING_MESSAGE = "Connecting to server...";
}
My program hangs at the line Connection con = DriverManager.getConnection(DB_URL, USER, PASS); and my main problem is that it does not even throw an exception, it just stays there.
USER, PASS and DB_URL are definitely correct.
It sounds like your ip/port is getting blocked/dropped. That's typically the case when a connection does nothing (as opposed to getting refused or failed login). Make sure your Security Group is set up properly. http://aws.amazon.com/rds/faqs/#31
I am new to programming and i am trying to make an small Java swing application using netbeans IDE and i have designed the Form and created an table too i used the following code to insert data into database from the form but i am getting many errors please help me to correct this code:
import java.sql.*;
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/userdb";
static final String USER="root";
static final String PASS="toor";
Connection conn = null;
Statement stmt = null;
static final String d_unit=jTextField2.getText();
static final String d_name=jTextField3.getText();
static final String d_dob=jDateChooser2.getText();
//static final String d_gender="gender";
static final String d_age=jTextField4.getText();
static final String d_doorno=jTextField5.getText();
static final String d_street=jTextField6.getText();
static final String d_vc=jTextField7.getText();
static final String d_district=jTextField8.getText();
static final String d_pin=jTextField9.getText();
static final String d_phone=jTextField10.getText();
static final String d_mail=jTextField11.getText();
static final String d_occupations=jTextField12.getText();
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) values('"+d_unit+"','"+d_name+"','"+d_dob+"','"+d_age+"','"+d_doorno+"','"+d_street+"','"+d_vc+"','"+d_district+"','"+d_pin+"','"+d_phone+"','"+d_mail+"','"+d_occupations+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e)
{ }
}
You may not use the final String because, then you can't modify these Strings, and the other code is correct, but i think you can use the ? in the line:
String sql="INSERT INTO ´donors´ (unit,name) VALUES (?,?)";
//put the rest of the sentence
try {
PreparedStatement pdt = cn.prepareStatement(sql);
pdt.setString(1, jTextField2.getText();
pdt.setString(2, jTextField3.getText();
//put the rest of the code
int n1=pdt.executeUpdate();
if(n1>0)
{
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
}catch (SQLException ex) { }
Well, that's the largest way, but the most correct. I hope this helps.
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode = txtItemCode.getText();
String itemName = txtItemName.getText();
String unitPrice = txtUnitPrice.getText();
String qty = txtQty.getText();
String query = "insert into items values ('"+itemCode+"','"+itemName+"','"+unitPrice+"','"+qty+"')";
System.out.println(query);
try {
Connection c = DBClass.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Saved");
} catch (Exception e) {
e.printStackTrace();
}
// DBClass
import java.sql.Connection;
import java.sql.DriverManager;
/**
*
* #author Nadun
*/
public class DBClass {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/stock", "root", "123");
}
return connection;
}
}
Everything looks alright. Maybe the trouble is on your mysql database?
Check the data type of your row in mysql, if your data type in the current row is "int", then it should be like this
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
stmt.executeUpdate("insert into donors (name, age) values('"+d_name+"',,'"+Integer.valueOf(d_age.getText().toString())+"')");
JOptionPane.showMessageDialog(null,"Inserted Successfully!");
}
catch(Exception e){ }
}
You should be careful with data types. If your mysql row is int type then in your java you should give it int time as well.
I guess your data type of "name" row is text that use string, and your data type of "age" row is int?
I check your code is giving a string value from your java to your int mysql row. that's the error.
So you should convert the string to the int first
Integer.valueOf(d_age.getText().toString());
try proceeding like this for simplicity and less error-prone
String sql = "INSERT INTO donors(unit,name,dob,age,doorno,street,vc,district,pin,phone,mail,occupation) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
stmt.executeUpdate(sql);
This question already has answers here:
java.lang.ClassNotFoundException in spite of using CLASSPATH environment variable
(9 answers)
Closed 9 years ago.
I am trying to connect to mysql database (as part of the Vertrigo server) on my windows 7 pc, but it keeps throw me the "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".
Following is my code :
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.LinkedList;import java.util.List;
public class ShippingCompany {
private Connection conn;
private Statement stmt;
private List<Journey> journeyList;
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://172.16.127.38:3306/testRestricted";
public ShippingCompany(String dbUser, String dbPassword) throws Exception {
journeyList = new ArrayList<Journey>();
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(DB_URL, dbUser, dbPassword);
stmt = conn.createStatement();
} catch (SQLException e) {
System.out.println("SQL Exception:" + e);
}
}
public List<String> readAllPorts() throws SQLException{
List<String> allPorts = new ArrayList<String>();
String command = "SELECT * FROM Ports";
ResultSet rs = stmt.executeQuery(command);
while (rs.next()) { // database name string is in first column of result set
allPorts.add(rs.getString(2));
//In command concole, print out all ports
System.out.println(rs.getString(2));
}
return allPorts;
}
public List<Journey> getAllJourneys(String startPort, String startDate, String endPort){
return new LinkedList<Journey>();
}
private void findPaths(Journey journey, String endPort){
}
public void Close(){
}
public static void main(String[] args) throws Exception{
//TODO : entry point of the program
ShippingCompany sc = new ShippingCompany("root", "vertrigo");
sc.readAllPorts();
}
}
should be
You need to have mysql connector jar in your classpath while running the program. If you are running it through the command line then you can do something like this:
java -cp <.;path to sql jar> ShippingCompany
I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?