CRUD代码;
package jdbcCRUD;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* @auther SyntacticSugar
* @data 2018/9/12 0012下午 9:15
*/
public class Increase {
private static Connection conn;
private static PreparedStatement statement;
public static void main(String[] args) {
//
try {
conn = CrudUtils.getConnection();//工具类获取conn
// String sql = "insert into orders values(?,?,?)";
// statement = conn.prepareStatement(sql);
// statement.setInt(1, 4);
// statement.setString(2, "香香");
// statement.setFloat(3, 20);
// statement.executeUpdate();
// String sql = "delete from orders where id=?";
// statement = conn.prepareStatement(sql);
// statement.setInt(1, 4);
// statement.executeUpdate();
String sql = "update orders set id=?,name=?,price=? where id=4";
statement = conn.prepareStatement(sql);
statement.setObject(1, null);
statement.setString(2, "香皂");
statement.setFloat(3, 15);
statement.executeUpdate();
//
System.out.println("ok");
} catch (Exception e) {
e.printStackTrace();
} finally {
CrudUtils.closeResouce(statement, conn);//工具类关闭资源
}
}
}
封装的工具类;
package jdbcCRUD;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
/**
* @auther SyntacticSugar
* @data 2018/9/12 0012下午 9:45
*/
public class CrudUtils {
/**
* 获取连接
* @throws ClassNotFoundException
* @throws IOException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException, IOException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Properties properties = new Properties();
properties.load(new FileReader("config/jdbc.properties"));
String url = properties.getProperty("jdbc.url");
String user = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
return DriverManager.getConnection(url, user, password);
}
/**
*
* 关闭资源;
*/
public static void closeResouce(PreparedStatement statement,Connection conn) {
try {
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}