hi~我是郑突突
今天我们学习:JDBC配置及基本操作
场景:数据库是我们一定要掌握的。JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。
首先要添加mysql-connector-java jar包
直接在pom文件下添加maven依赖就可以了。
现在大多是6.x版,我之前使用了但无法解决出现的问题,之后会补充6.x版本下的使用。
首先加载驱动程序
一句话总结:将mysql驱动注册到DriverManager中去,为了之后使用Connection类。具体原因
接下来我们要去链接数据库。
这时候需要Connection类的对象和数据库的URL,用户名和密码
在这里你可以下载一个Mysql数据库管理工具Navicat,便于查看数据库。
private static Connection conn = null;
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
然后通过这个Connection对象去创建一个Statement对象,Statement用于执行Sql语句。
添加表,我们来创建一个student表
private static void createTable() {
try {
String tableName;
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
stmt = conn.createStatement();
System.out.println("Please input the table name of which you want to create:");
String getchar = in.nextLine(); //作用相当于C语言的getchar()
tableName = in.nextLine();
String sql = "CREATE TABLE " + "student " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println(tableName + "table already create successful!");
}catch(SQLException e){
//Handle errors for JDBC
e.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
删除student表
修改一下Sql语句就可以了
String tableName;
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
stmt = conn.createStatement();
String getchar = in.nextLine(); //作用相当于C语言的getchar()
System.out.println("Please input the table name of which you want to delete:");
tableName = in.nextLine();
String sql = "DROP table " + tableName;
stmt.executeUpdate(sql);
System.out.println(tableName + "table already delete successful!");
不要忘了try catch 哦。
还有其他操作的话,只要修改Sql语句即可。
不是很懂的,这里有例子。
另外,如果有读者知道如何不通过降低版本的手段去解决–>
使用mysql-connector-java-6.0.6版本时,出现Caused by: java.sql.SQLNonTransientConnectionException: CLIENT_PLUGIN_AUTH is required错误。
请教教我,给您拜个早年!