例子:
1.在数据库中建立如下表
2. 在MyEclipse里按本主博客文MyEclipse 03_jdbc连接数据库,注意数据库名要一致
运行后在Navicat里如下:
代码如下:
package net;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Conn {
public static void main(String[] args){
try{
//加载MySql的驱动类
Class.forName("com.mysql.cj.jdbc.Driver") ;
//jdbc:mysql:localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
String url = "jdbc:mysql://localhost:3306/shujuku" ;
String username = "root";
String password = "root";
Connection Conn = null;
try{
Conn = DriverManager.getConnection(url , username , password ) ;
Statement stmt = Conn.createStatement();
stmt.executeUpdate("insert into dog values(005,'问子',80,90,'藏獒犬')");
} catch(SQLException se){
System.out.println("数据库连接失败!");
se.printStackTrace() ;
} finally{
if(Conn!=null ){
try {
Conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
catch(ClassNotFoundException e){
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace() ;
}
}
}