首先获取JDBC驱动程序,例如mysql的Connector/J - 将jar添加到项目中.然后,您可以访问如下数据库:
公共类mysqlTest {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String protocol = "jdbc:mysql://localhost/";
String database = "database";
String username = "mysqlUsername";
String password = "mysqlPassword";
Properties props = new Properties();
props.put("user", username);
props.put("password", password);
Connection conn;
Statement s;
ResultSet rs;
String createTableStatment = "CREATE TABLE test ( `id` INTEGER NOT NULL)";
String insertStatment = "INSERT INTO test VALUES(1)";
String selectQuery = "SELECT * FROM test";
try {
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(protocol + database,props);
conn.setAutoCommit(true);
s = conn.createStatement();
s.execute(createTableStatment);
s.execute(insertStatment);
rs = s.executeQuery(selectQuery);
while (rs.next()){
System.out.println("id = "+rs.getString("id"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
677 次 |
| 最近记录: |