java - JDBC connecting to MySQL on Amazon ec2 -
i'm little new @ that, after starting ec2 instance, , installing mysql instance through rds, manage connect through mysql workbench using ssh (.pem file).
my problem can't seem have right, when i'm trying connect jdbc, how authentication suppose done?
here code, hope can give me hint on how proceed:
public void create_table(){ connection c = null; statement stmt = null; try { class.forname("com.mysql.jdbc.driver"); c = drivermanager.getconnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password"); // c = drivermanager.getconnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", ""); system.out.println("opened database successfully"); stmt = c.createstatement(); string sql = "create table users " + "(id int primary key ," + " device text not null, " + " name text not null)"; stmt.executeupdate(sql); stmt.close(); c.close(); } catch ( exception e ) { system.err.println( e.getclass().getname() + ": " + e.getmessage() ); system.exit(0); }
edit
i forgot few important details...
- i wrote code in java using jersey , servelt.
- i uploaded war file ec2 instance.
now after both web-app , mysql server running on same instance, i want build communication..
thank you!
your sql syntax
incorrect. text
values inserted varchar
type in sql
. can change length of text value depending on need changing value in bracktes in varchar(here)
. try code.
//step 1. import required packages import java.sql.*; public class jdbcexample { // jdbc driver name , database url static final string jdbc_driver = "com.mysql.jdbc.driver"; static final string db_url = "jdbc:mysql://localhost:3306/students"; // database credentials static final string user = "username"; static final string pass = "password"; public static void main(string[] args) { connection conn = null; statement stmt = null; try{ //step 2: register jdbc driver class.forname("com.mysql.jdbc.driver"); //step 3: open connection system.out.println("connecting selected database..."); conn = drivermanager.getconnection(db_url, user, pass); system.out.println("connected database successfully..."); //step 4: execute query system.out.println("creating table in given database..."); stmt = conn.createstatement(); string sql = "create table users " + "(id integer not null," + " device varchar(255) not null," + " name varchar(255) not null,"+ "primary key (id))"; stmt.executeupdate(sql); system.out.println("created table in given database..."); }catch(sqlexception se){ //handle errors jdbc se.printstacktrace(); }catch(exception e){ //handle errors class.forname e.printstacktrace(); }finally{ //finally block used close resources try{ if(stmt!=null) conn.close(); }catch(sqlexception se){ }// nothing try{ if(conn!=null) conn.close(); }catch(sqlexception se){ se.printstacktrace(); }//end try }//end try system.out.println("goodbye!"); }//end main }//end jdbcexample
Comments
Post a Comment