import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
public class Connect {
String DBDRIVER="com.mysql.jdbc.Driver";
String DBURL="jdbc:mysql://localhost:3306/test";
String DBUSER="root";
String DBPWD="1995nian";
Connection conn=null;
public Connect(){
try {
Class.forName(DBDRIVER);
conn=DriverManager.getConnection(DBURL,DBUSER,DBPWD);
//System.out.println("数据库连接成功");
} catch (ClassNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public Connection getCon(){
return conn;
}
public void doSql(double x,double y){
Connection connection=new Connect().getCon();
try {
String sql="insert into tmp values(?,?)";
PreparedStatement ps=connection.prepareStatement(sql);
ps.setDouble(1, x);
ps.setDouble(2, y);
ps.execute();
ps.close();
connection.close();
} catch (Exception e) {
// TODO: handle exception
}
}
public void closeCon(){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
public static void main(String[] args){
Connect connect=new Connect();
Connection connection=connect.getCon();
//String sql="insert into tmp values(30,50)";
connect.doSql(30, 50);
}
}
这是样板,项目还要引入mysql的数据库驱动