jdbc读MySQL_java jdbc方式读写mysql

import java.io.UnsupportedEncodingException;

import java.sql.*;

public class Main {

public static void main(String[] args) {

Connection connection = null;

Connection cnn = null;

PreparedStatement preparedStatement = null;

ResultSet resultSet = null;

try {

Class.forName("com.mysql.jdbc.Driver");

}catch (ClassNotFoundException e){

System.out.println("获取驱动类失败");

e.printStackTrace();

}

try {

connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");

cnn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");

}catch (SQLException e){

System.out.println("连接数据库失败");

e.printStackTrace();

}

String sql = "select * from news limit 20";

try {

preparedStatement = connection.prepareStatement(sql);

}catch (SQLException e){

e.printStackTrace();

}

try {

resultSet = preparedStatement.executeQuery(sql);

}catch (SQLException e){

e.printStackTrace();

}

try {

while(resultSet.next())

{

//int id = resultSet.getInt("ID_");

String title = resultSet.getString("contenttitle");

String content = resultSet.getString("content");

String sql1="insert into news1(title,content) values(?,?)";

PreparedStatement pstmt=cnn.prepareStatement(sql1);

String title_iso88591 = new String(title.getBytes("UTF-8"),"ISO8859-1");

String title_utf8 = new String(title_iso88591.getBytes("ISO8859-1"),"UTF-8");

System.out.println(title_utf8);

pstmt.setString(1, title_utf8);

String content_iso88591 = new String(content.getBytes("UTF-8"),"ISO8859-1");

String content_utf8 = new String(content_iso88591.getBytes("ISO8859-1"),"UTF-8");

System.out.println(content_utf8);

pstmt.setString(2, content_utf8);

int res=pstmt.executeUpdate();

if(res>0){

System.out.println("数据录入成功");

}

pstmt.close();

//System.out.println("Content title:"+contenttitle+ "\n" + "content:"+content);

//System.out.println("id:"+id+" name:"+name+" creator:"+creator);

}

}catch (SQLException e){

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

if(resultSet!=null)

{

try {

preparedStatement.close();

}catch (SQLException e){

e.printStackTrace();

}

}

if(connection!=null)

{

try {

connection.close();

cnn.close();

}catch (SQLException e){

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值