原来JDBC连接数据库连接竟然这么简单!
- 加载驱动
- 创建连接
- 进行预编译
- 执行sql语句
- 释放资源
代码1
public class Demo01 {
public static void main(String[] args) throws Exception{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day06", "root", "root");
Statement stm= conn.createStatement();
int r=stm.executeUpdate("insert into stu(id,username,age)values(6,'刘备',45)");
if(r>0) {
System.out.println("执行成功");
}else {
System.out.println("失败");
}
//System.out.println("受影响行数:"+r);
stm.close();
conn.close();
}
}
代码2
public class Demo2 {
public static void main(String[] args) {
Connection conn=null;
Statement stm=null;
ResultSet result=null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06","root", "root");
stm=conn.createStatement();
//int r=stm.executeUpdate("insert into stu(id, username,age) values(7,'貂蝉',18)");
//int r=stm.executeUpdate("delete from stu where id=1");
//int r=stm.executeUpdate("update stu set username='西施' where id=4");
result=stm.executeQuery("select* from stu");
if(result!=null) {
System.out.println("编号\t姓名\t年龄");
}
while(result.next()) {
int id=result.getInt(1);
String username=result.getString("username");
int age=result.getInt("age");
System.out.println(id+"\t"+username+"\t"+age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放结果
try {
if(result!=null) {
result.close();
}
if(stm!=null) {
stm.close();
}
if(conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
注意
localhost:默认的是本机的端口号(127.0.0.1)
Mysql的默认端口号:3306
第一个root:数据库名
第二个root:数据库密码
简单的总结JDBC连接数据库5个字:加连预执释
jar包: