插入
/*
JDBC注册驱动
,;E:\驱动连接操作\mysql-connector-java-5.1.15-bin.jar;
*/
//JDBC注册驱动六步骤:
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Driver;
import java.sql.Connection;
import java.sql.Statement;
public class JDBCTest01{
public static void main(String[] args){
Statement stmt=null;
Connection conn=null;
//1.注册驱动
try{
Driver driver=new com.mysql.jdbc.Driver();
//多态,父类引用指向子类对象
DriverManager.registerDriver(driver);
//2.获取连接
/*
url:统一资源定位符(网络中某个资源的绝对路径)
http://www.baidu.com/这就是url;
url包括那几部分?
协议
ip
PORT(端口)
资源名
http://182.61.200.7:80/index.html
http:// 通信协议
182.61.200.7 服务器IP地址
80 服务器上软件上某个资源名
*/
String url="jdbc:mysql://127.0.0.0:3306/student";
String user="root";
String password="123456";
conn=DriverManager.getConnection(url,user,password);
System.out.println("数据库连接对象= "+conn);
//3.获取数据库操作对象(Statement专门执行sql语句的)
stmt= conn.createStatement();
//4.执行sql
String sql="insert into t_user(username) values('ass')";
int count=stmt.executeUpdate(sql);
System.out.println(count ==1 ? "暴怒才能成功共" : "保存失败");
}catch(SQLException e){
e.printStackTrace();
}finally{
//5.处理查询结果集
//6.释放资源
//为保证资源一定释放,在finally语句块中关闭资源
//并且要遵守从小到大原则以此关闭
//分别对其try
try{
if(stmt !=null){
stmt.close();
}
}catch(SQLException e){
e.printStackTrace();}
try{
if(conn !=null){
stmt.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}