简单的Java连接MySQL数据库
最近需要用到Java连接MySQL数据库
Connection conn = null;
Statement stmt = null;
try {
// 连接数据库
Class.forName("com.mysql.jdbc.Driver");
//数据库路径
String dburl = "jdbc:mysql://localhost:3306/test";
//root数据库账号 admin数据库密码
conn = DriverManager.getConnection(dburl, "root", "admin");
//连接成功输出
System.out.println("connection built");
} catch (SQLException e) {
//捕捉数据库异常
e.printStackTrace();
} catch (ClassNotFoundException e) {
//捕捉无法找到指定的类异常
e.printStackTrace();
}
//如果需要执行sql,需要创建一张表
String sql="create table if not exists test (id int(32) not null,name text not null,primary key (id)) engine=InnoDB DEFAULT CHARSET=utf8";
//获取一个可以执行sql语句的对象
stmt = conn.createStatement();
//执行sql,Statement类型执行sql全部是已知的值
stmt.executeUpdate(sql);
//PrepareStatement类型执行sql用问号代替值,后面通过set设置