Java JDBC MySQL Connection and Car Table Management

Computer science2.75 KB

Java JDBC Connection and Cars Table in MySQL

public static Connection conexionBD(String BDNombre) throws SQLException {
Connection con = null;
try {
System.out.println("Connecting...");
String controlador = "com.mysql.jdbc.Driver";
Class.forName(controlador).newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bdtest", "usuario", "contraseña");
System.out.println("Connection succeeded!");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void createCOCHES(Connection con, String BDNombre) throws SQLException {
String createString = "create table if not exists " + BDNombre + ".coches " +
"(matricula varchar(8) not null," +
"marca varchar(40) not null," +
"modelo varchar(40) not null," +
"color varchar(20) not null," +
"anio integer not null," +
"precio integer not null," +
"primary key (matricula))" + " Engine=InnoDB";
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
} catch (SQLException e) {
printSQLException(e);
} finally {
stmt.close();
}
}
public static void seleccionarCOCHES(Connection con, String BDNombre) throws SQLException {
Statement stmt = null;
String query = "select * from " + BDNombre + ".coches";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String matricula = rs.getString("matricula");
String marca = rs.getString("marca");
String modelo = rs.getString("modelo");
String color = rs.getString("color");
int anio = rs.getInt("anio");
int precio = rs.getInt("precio");
//System.out.println(team_id + eq_nombre + estadio + poblacion + provincia + cod_postal);
System.out.printf("%12s %12s %12s %12s %6d %8d", matricula, marca, modelo, color, anio, precio);
System.out.println("**************");
}
} catch (SQLException e) {
printSQLException(e);
} finally {
stmt.close();
}
}

Download

PDF Word HTML