//使用预处理来连接数据库
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
{
//加载mysql驱动
Class.forName(driver);
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
{
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
}