preparestatement

来源:互联网 发布:php restful 框架 编辑:程序博客网 时间:2024/05/18 02:56
 //使用预处理来连接数据库



import java.sql.*;

public class  DDD{

public static void main(String []args)

{

  String driver ="com.mysql.jdbc.Driver";

  String URL="jdbc:mysql://localhost:3306/databasesname";

  String username="root";

  String pass="admin";

Connection  con=null;

PreparedStatement pre= null;

ResultSet res=null;

try

 {

// java反射获取驱动类
Class.forName(driver);

// Driver drivers= (Driver)Class.forName(driver).newInstance();

// 向驱动管理类中注册驱动类,我们获取connection 是通过DriverManager的getConnection(url) 方法获取,其实就是通过这个url 的协议来匹配到注册的驱动类,在通过驱动类来获取指定url的数据库的链接

//DriverManager.registerDriver(driver);

// 通过DriverManager的驱动获取connection之后驱动一直在内存中

con= DriverManager.getConnection(URL,username,pass);
//设置提交方式,这里取消了自动提交
con.setAutoCommit(false);

pre= con.prepareStatement("insert into table_user values(?,?,?);"); //占位符没有实际的值
//调用方法来赋值
pre.setString (1,"xiaoming");

pre.setInt(2,20);

pre.setString(3,"m");

pre.executeUpdate();

pre.clearParameters();

pre.setString(1,"haidong");

pre.setInt(2,21);

pre.setString(3,"m");

pre.executeUpdate();

pre.clearParameters();

//我们取消了自动提交方式所以我们手动提交

con.commit();

res=pre.executeQuery("select* from  table_user ");

while(res.next())

{

System.out.println(res.getString(1));

System.out.println(res.getInt(2));

System.out.println(res.getString(3));

}

}



catch(ClassNotFoundException e)

{

e.printStackTrace();

}

catch(SQLException e)

{

e.printStackTrace();

}

finally

{

if(pre!= null)

{

try

{
//  释放资源
pre.close();

}

catch(SQLException e)

{

e.printStackTrace();

}

}

if(con!= null)

{

try

{
// 释放资源,释放链接,释放后如果不连接就有可能会被gc 收集。
con.close();

}

catch(SQLException e)

{

e.printStackTrace();

}

}

}

}

 

}
原创粉丝点击