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

MYSQL
轻松掌握如何从命令行启动mysqld服务器
教你快速掌握怎样在Windows下升级MySQL
解析:安装 MySQL时如何选择安装软件包
解析:快速的掌握 MySQL支持的操作系统
MySQL环境下导入数据时是否需要禁用索引
配置高可用性的MySQL服务器负载均衡群集
使用ERWin进行基于MySQL数据库的物理设计
数据库应用经验:如何简单安装MySQL数据库
DBA应当了解的MySQL客户端程序启动选项
将MySQL 5.0下的数据导入到MySQL 3.23中
讲解MaxDB数据库和MySQL数据库的主要差别
实例讲解如何利用crontab定时备份MySQL
个人经验总结:完全卸载MySQL数据库5.0
如何在Unix系统环境下安装MySQL数据库
适宜做简单搜索的MySQL数据库全文索引
教你在MySQL 5.0以上版本中配置主从库
经验总结:修改MySQL默认密码的具体步骤
将后台数据从Berkeley的文件DB转到MySQL
详细介绍查询优化技术在现实系统中的运用
MySQL数据库中对前端和后台进行系统优化

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 78 ::
收藏到网摘: 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();

}

}

}

}