JDBC连接示例
1.加载mysql-jdbc的jar包mysql-connector-java-5.0.8-bin.jar。
2.初始化驱动
通过Class.forName("com.mysql.jdbc.Driver");
初始化驱动类com.mysql.jdbc.Driver
3.建立与数据库的Connection连接
这里需要提供:数据库所处于的ip:127.0.0.1 (本机)
数据库的端口号: 3306 (mysql专用端口号)
数据库名称 how2java
编码方式 UTF-8
账号 root
密码 admin
4.创建Statement
Statement是用于执行SQL语句的,比如增加,删除
5.执行SQL语句。
6.关闭连接
数据库的连接是有限资源,相关操作结束后,养成关闭数据库的好习惯
先关闭Statement
后关闭Connection
注意异常的抛出的书写,首先要判断是否加载成功(是否为null),然后再对相应的资源进行释放。
示例代码:
package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
public static void main(String [] args){
Statement statement=null;
Connection connection=null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("database load successfully!");
connection= DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
"root",
"admin"
);
System.out.println("连接成功,获取连接对象:"+connection);
statement=connection.createStatement();
System.out.println("获取Statement对象:"+statement);
for (int id=1;id<10;++id){
String sql="insert into hero values ("+id+","+"'英雄"+id+"'"
+","+200+","+50+");";
statement.execute(sql);
}
System.out.println("执行插入语句成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}