import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import org.junit.Test; public class Demo2 { private String url = "jdbc:mysql://localhost:3306/test1"; private String user = "root"; //用户名 private String password ="123"; //密码 /** * 执行DDL语句(创建表) */ @Test public void test1(){ Statement stmt = null; Connection conn = null; try { //1.驱动注册程序 Class.forName("com.mysql.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection(url, user, password); //3.创建Statement stmt = conn.createStatement(); //4.准备sql String sql = "CREATE TABLE student2(id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),gender VARCHAR(2))"; //5.发送sql语句,执行sql语句,得到返回结果 int count = stmt.executeUpdate(sql); //6.输出 System.out.println("影响了"+count+"行!"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally{ //7.关闭连接(顺序:后打开的先关闭) if(stmt!=null) try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } if(conn!=null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } }
Jdbc程序中的Connection,它用于代表数据库的链接,Collection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的,这个对象的常用方法: createStatement():创建向数据库发送sql的statement对象。 prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。 prepareCall(sql):创建执行存储过程的CallableStatement对象。 setAutoCommit(boolean autoCommit):设置事务是否自动提交。 commit() :在链接上提交事务。 rollback() :在此链接上回滚事务。