java 新闻编辑,使用JDBC编辑新闻信息 1、 创建 News.java ,定义一个新闻类,使用 JavaBean...
时间: 2024-05-04 14:21:36 浏览: 117
好的,下面是一个简单的示例:
首先,我们需要定义一个 News 类,包含新闻的标题、作者、内容和发布时间等属性:
```java
public class News {
private int id;
private String title;
private String author;
private String content;
private Date publishTime;
// getter 和 setter 方法
}
```
接下来,我们需要使用 JDBC 连接数据库,将新闻信息存储到数据库中。首先,我们需要加载数据库驱动:
```java
Class.forName("com.mysql.jdbc.Driver");
```
然后,我们需要创建一个 Connection 对象,连接到数据库:
```java
String url = "jdbc:mysql://localhost:3306/news_db";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
```
接下来,我们可以使用 PreparedStatement 对象向数据库中插入新闻信息:
```java
String sql = "INSERT INTO news (title, author, content, publish_time) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, news.getTitle());
pstmt.setString(2, news.getAuthor());
pstmt.setString(3, news.getContent());
pstmt.setTimestamp(4, new Timestamp(news.getPublishTime().getTime()));
int result = pstmt.executeUpdate();
```
最后,我们需要关闭数据库连接:
```java
pstmt.close();
conn.close();
```
完整的代码示例如下:
```java
import java.sql.*;
import java.util.Date;
public class News {
private int id;
private String title;
private String author;
private String content;
private Date publishTime;
// getter 和 setter 方法
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
String url = "jdbc:mysql://localhost:3306/news_db";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
// 插入新闻信息
News news = new News();
news.setTitle("Java 新闻标题");
news.setAuthor("Java 编辑");
news.setContent("Java 新闻内容");
news.setPublishTime(new Date());
String sql = "INSERT INTO news (title, author, content, publish_time) VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, news.getTitle());
pstmt.setString(2, news.getAuthor());
pstmt.setString(3, news.getContent());
pstmt.setTimestamp(4, new Timestamp(news.getPublishTime().getTime()));
int result = pstmt.executeUpdate();
System.out.println("插入了 " + result + " 条新闻信息。");
// 关闭数据库连接
pstmt.close();
conn.close();
}
}
```
阅读全文