復制代碼 代碼如下:
String driverName="com.mysql.jdbc.Driver";
String connectiionString="jdbc:mysql://10.5.110.239:3306/test?"+"user=root&password=chen&characterEncoding=utf-8";
Connection connection=null;
try {
Class.forName(driverName);//這里是所謂的數據庫驅動的加載
connection=(Connection) DriverManager.getConnection(connectiionString);//這里就是建立數據庫連接
System.out.println("數據庫連接成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
復制代碼 代碼如下:
Statement statement=(Statement) dUtil.getConnection().createStatement();
String sql="delete from diary where int count=statement.executeUpdate(sql);
System.out.println("刪除成功");
復制代碼 代碼如下:
String sql="insert into diary(title,content,authorname,time) values(?,?,?,now())";
try {
PreparedStatement preparedStatement=(PreparedStatement) dUtil.getConnection().prepareStatement(sql);
String String content=diary.getContent();
String authorname=diary.getAuthorName();
preparedStatement.setString(1, title);
preparedStatement.setString(2, content);
preparedStatement.setString(3, authorname);
復制代碼 代碼如下:
ResultSet resultSet=statement.executeQuery(sql);
while (resultSet.next()) {
Diary diary=new Diary();
diary.setAuthorName(resultSet.getString("authorname"));
diary.setContent(resultSet.getString("content"));
diary.setTitle(resultSet.getString("title"));
diary.setId(resultSet.getInt("id"));
Date time=resultSet.getDate("time");
復制代碼 代碼如下:
public static void closeConnection(ResultSet resultSet,PreparedStatement preparedStatement, Connection connection) throws SQLException {
if (resultSet!=null) resultSet.close();
if (preparedStatement!=null) preparedStatement.close();
if(connection!=null&&connection.isClosed()==false) connection.close();
System.out.println("數據庫關閉");
}
新聞熱點
疑難解答