Asked By
jaysonm009
0 points
N/A
Posted on - 09/22/2011
Hello, I have a question about how can I create a database with Java and how can I also connect that database to my Application or Software.
What are the keys to create and connect the Database to my Application or Software?
Can you give me an Example ?
Thanks !
Answered By
dynamo
0 points
N/A
#126109
Creating and connecting database with JAVA
Hi,
I think this java code will help you create a database from java
import java.io.*;
import java.sql.*;
public class CreateDatabase{
public static void main(String[] args) {
System.out.println("Database creation example!");
Connection con = null; //first you have to create a connection
try{
Class.forName("com.mysql.jdbc.Driver");//then specify the connection name or the jdbc driver
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/databaseName","userName","password");/*after that, you have to connect to your RDBMS specifying the URL, username and password*/
try{
Statement st = con.createStatement();//buffer reader to
BufferedReader bf = new BufferedReader//get the database name from keyboard
(new InputStreamReader(System.in));
System.out.println("Enter Database name:");
String database = bf.readLine();
st.executeUpdate("CREATE DATABASE "+database);//actual creation of the database
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
This code will help you connect to a database :
import java.sql.*;
public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";//Server URL
String dbName = "dataBaseName";//DataBase name
String driver = "com.mysql.jdbc.Driver";//The driver class
String userName = "root"; //User name
String password = "root";//The password
try {
Class.forName(driver).newInstance();//Create new instance
conn = DriverManager.getConnection(url+dbName,userName,password);//Connect to the database
System.out.println("Connected to the database");
conn.close();//Close the connection to the database
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this will help.
P.S. If you have any other questions don't hesitate 🙂