当前位置: 首页 > 图文教程 > 数据库 > MYSQL > 巧用JDBC实现对MySQL的“增删改查”

MYSQL
初学者在使用MySQL时必须了解的注意事项
实例剖析:MySQL数据库优化详解
RedHat 9.0下用rpm包安装mysql
MYSQL 数据库同步
Windows XP操作系统下的MYSQL安装过程
Mysql入门系列:MySQL数据目录的位置
Mysql入门系列:MYSQL日志文件维护
Mysql入门系列:优化MYSQL服务器
MySQL数据库磁盘优化
MySQL数据库中应当如何实施info()函数
解析:怎样在MySQL中获得更好的搜索结果
怎样修改 MySQL数据库中的密码
如何正确编写高质量高性能的MySQL语法
细化解析:MySQL 搜索中的大小写敏感性
如何正确的解决 MySQL中忽略用户的现象
详解MySQL数据库中Show命令的用法
轻松掌握 MySQL的数字类型以及建库策略
怎样处理 MySQL中与文件许可有关的问题
教你快速实现 MySQL查询结果的分页显示
解析:MySQL对“服务器端光标”的限制

MYSQL 中的 巧用JDBC实现对MySQL的“增删改查”


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 44 ::
收藏到网摘: n/a

用JDBC实现对MySQL的“增删改查”:

以下为引用的内容:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import com.bean.NoticeBean;

public class JDBCTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Connection conn=null;

Statement stmt=null;

ResultSet rs=null;

try {

String driverName="com.mysql.jdbc.Driver";

Class.forName(driverName);

String url="jdbc:mysql://localhost:3306/java?

useUnicode=true&characterEncoding=gb2312";

conn=DriverManager.getConnection(url,"root","root");

System.out.println("连接MySql成功!!!");

stmt=null;

rs=null;

String strSql=null;

NoticeBean bean=null;

String title=null;

String content=null;

try {

title="标题";

content="内容";

strSql="INSERT INTO notice(title,content) VALUES('"+title+"','"+content+"')";

stmt=conn.createStatement();

stmt.executeUpdate(strSql);

System.out.println("插入语句执行成功:"+strSql);

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.println("插入失败");

}

strSql="select * from notice";

stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_READ_ONLY);

rs=stmt.executeQuery(strSql);

if(rs.next()){

int id=rs.getInt("id");

title =rs.getString("title");

content=rs.getString("content");

if(rs.next()){

bean=new NoticeBean(id,title,content);

}

System.out.println("notice第一行数据是"+bean.getId()+" "+bean.getTitle()

+" "+bean.getContent());

}

try {

strSql="delete from notice";

stmt=conn.createStatement();

stmt.executeUpdate(strSql);

System.out.println("删除完成");

} catch (RuntimeException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.println("删除失败");

}

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

try {

if(rs!=null){

rs.close();

rs=null;

}

if(stmt!=null){

stmt.close();

stmt=null;

}

if(conn!=null){

conn.close();

conn=null;

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}