package com.bmi.dao;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
public class JDBCConnection {
//1.准备数据 数据库路径 用户名 密码
public static final String url = "jdbc:mysql://localhost:3306/bmi";//jdbc连接本机3306端口下bmi数据库
public static final String user = "root";
public static final String password ="";
public static final String driver ="com.mysql.jdbc.Driver";
public java.sql.Connection connection;
public PreparedStatement prepareStatement;
//2.创建连接
//构造器public JDBCConnection(){}
public void Connection(String sql){
//加载驱动
try{
Class.forName(driver);
System.out.println("加载成功");
connection = DriverManager.getConnection(url, user, password);
System.out.println("连接成功");
//编译sql
prepareStatement = connection.prepareStatement(sql);
}catch(Exception e){//需要捕捉最大的异常
e.printStackTrace();
}
}
/* public static void main(String[] args){
new JDBCConnection().Connection();
}*/
//增加数据的方法
public boolean insertBmi(String date,String height,String weight,String bmi){
//字符串类型的sql 没有任何执行的能力
String sql = "insert into bmi(data,height,weight,bmi) value";
//编译可执行sql语句
JDBCConnection jd = new JDBCConnection();
jd.Connection(sql);
boolean success = false;
try {
jd.prepareStatement.setString(1, date);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jd.prepareStatement.setString(2, height);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jd.prepareStatement.setString(3, weight);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jd.prepareStatement.setString(4, bmi);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
int i =jd.prepareStatement.executeUpdate();
if (i>0){
success = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//执行
return success;
}
}