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

MYSQL
五种MySQL数据库可靠性方案的分析和比较
怎样在Mysql中直接储存图片
mysql的本地备份和双机相互备份脚本
详细讲解Linux环境下MySQL 5.1安装步骤
实例讲解在MySQL中如何导出整个数据库
讲解MySQL索引的概念及数据库索引的应用
教你在MySQL中快速复制表格作为测试数据
删除完全重复和部分关键字段重复的记录
MySQL各存储引擎的区别及其启动方法
MySQL在网络安全方面采取的主要措施
在MySQL中执行SQL语句时的几个注意点
MySQL改善数据装载操作效率的策略
设计高效合理的MySQL查询语句讲解
MySQL用户Root密码为弱口令的攻击
MySQL数据库接口的VC具体实现与应用
在MySQL数据库增加新用户权限简介
MySQL中文模糊检索问题的解决方法
MySQL的数据类型和建库策略详解
利用图形界面从SQL导入导出到MySQL
MySQL数据库应该如何对抗解密高手

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


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

}

}

}

}