「java数据库操作语句」javasql语句
今天给各位分享java数据库操作语句的知识,其中也会对javasql语句进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
在Java中如何对数据库中的数据进行操作?
package com.dao;import java.sql.*;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;public class BaseDao {
/**
* 创建数据库连接及关闭
*/
// 打开连接
public static Connection getConnection() {
Connection con = null; /*************************** oracl 的连接 ***************************************/
// try { // Class.forName("oracle.jdbc.driver.OracleDriver");
// con = DriverManager.getConnection(
// "jdbc:oracle:thin:@127.0.0.1:1521:orcl", "bbs", "sa");
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException e) {
// e.printStackTrace();
// }
/******************************* sqlerver 的连接 ******************************/
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://127.0.0.1:1433;databasename=bbs", "sa",
"zhou");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
/*********************************************************************/
return con;
} // 关闭
public static void closeAll(Connection connection,
PreparedStatement pStatement, ResultSet res) {
try {
if (connection != null (!connection.isClosed())) {
connection.close();
}
if (res != null) {
res.close();
res = null;
}
if (pStatement != null) {
pStatement.close();
pStatement = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
对数据库增删改查package com.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;import com.entity.News;public class NewsDao {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
/**
* 添加新闻
* @param news
* @return
*/
public boolean newsAdd(News news){
boolean result=false;
String sql="insert into news values(?,?)";
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
pstmt.setString(1, news.getContent());
pstmt.setString(2, FormatTime.newTime());
int i = 0;
i = pstmt.executeUpdate();
if (i 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 修改新闻
* @param news
* @return
*/
public boolean updateNews(News news){
boolean result=false;
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement("update news set content=? ,writedate=? where newsid=?");
pstmt.setString(1, news.getContent());
pstmt.setString(2, FormatTime.newTime());
pstmt.setInt(3, news.getNewsID());
int i = 0;
i = pstmt.executeUpdate();
if (i 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 删除新闻
* @param news
* @return
*/
public boolean deleteNews(News news){
boolean result=false;
String sql=String.format("delete from news where newsid=%d", news.getNewsID());
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
int i = 0;
i = pstmt.executeUpdate();
if (i 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 删除新闻 重载
* @param newsId
* @return
*/
public boolean deleteNews(int newsId){
boolean result=false;
String sql=String.format("delete from news where newsid=%d", newsId);
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
int i = 0;
i = pstmt.executeUpdate();
if (i 0)
result = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 查询所有的新闻
* @return
*/
public ListNews selectAllNews(){
ListNews list=new ArrayListNews();
String sql="select * from Users";
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()){
News news=new News();
news.setNewsID(rs.getInt(1));
news.setContent(rs.getString(2));
news.setWriteDate(rs.getString(3));
list.add(news);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeAll(rs, pstmt, con);
}
return list;
}
/**
* 查询单个
* @return
*/
public News selectOneNews(){
News news=new News();
con=BaseDao.getConnection();
try {
pstmt=con.prepareStatement("select top 1 * from news order by newsid desc");
rs=pstmt.executeQuery();
while(rs.next()){
news.setNewsID(rs.getInt(1));
news.setContent(rs.getString(2));
news.setWriteDate(rs.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
BaseDao.closeAll(rs, pstmt, con);
}
return news;
}
}
实体类package com.entity;import java.io.Serializable;
public class News implements Serializable{
private int newsID;
private String content;
private String writeDate; public News() {
super();
// TODO Auto-generated constructor stub
} public News(String content, String writeDate) {
super();
this.content = content;
this.writeDate = writeDate;
} public News(int newsID, String content, String writeDate) {
super();
this.newsID = newsID;
this.content = content;
this.writeDate = writeDate;
} public int getNewsID() {
return newsID;
} public void setNewsID(int newsID) {
this.newsID = newsID;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public String getWriteDate() {
return writeDate;
} public void setWriteDate(String writeDate) {
this.writeDate = writeDate;
}
}
java中使用JDBC完成数据库操作的基本步骤是什么?
创建一个以JDBC连接数据库的程序,包含7个步骤: \x0d\x0a 1、加载JDBC驱动程序: \x0d\x0a 在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机), \x0d\x0a 这通过java.lang.Class类的静态方法forName(String className)实现。 \x0d\x0a 例如: \x0d\x0a try{ \x0d\x0a //加载MySql的驱动类 \x0d\x0a Class.forName("com.mysql.jdbc.Driver") ; \x0d\x0a }catch(ClassNotFoundException e){ \x0d\x0a System.out.println("找不到驱动程序类 ,加载驱动失败!"); \x0d\x0a e.printStackTrace() ; \x0d\x0a } \x0d\x0a 成功加载后,会将Driver类的实例注册到DriverManager类中。 \x0d\x0a 2、提供JDBC连接的URL \x0d\x0a •连接URL定义了连接数据库时的协议、子协议、数据源标识。 \x0d\x0a •书写形式:协议:子协议:数据源标识 \x0d\x0a 协议:在JDBC中总是以jdbc开始 \x0d\x0a 子协议:是桥连接的驱动程序或是数据库管理系统名称。 \x0d\x0a 数据源标识:标记找到数据库来源的地址与连接端口。 \x0d\x0a 例如:(MySql的连接URL) \x0d\x0a jdbc:mysql: \x0d\x0a //localhost:3306/test?useUnicode=truecharacterEncoding=gbk ; \x0d\x0a useUnicode=true:表示使用Unicode字符集。如果characterEncoding设置为 \x0d\x0a gb2312或GBK,本参数必须设置为true 。characterEncoding=gbk:字符编码方式。 \x0d\x0a 3、创建数据库的连接 \x0d\x0a •要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象, \x0d\x0a 该对象就代表一个数据库的连接。 \x0d\x0a •使用DriverManager的getConnectin(String url , String username , \x0d\x0a String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和 \x0d\x0a 密码来获得。 \x0d\x0a 例如: \x0d\x0a //连接MySql数据库,用户名和密码都是root \x0d\x0a String url = "jdbc:mysql://localhost:3306/test" ; \x0d\x0a String username = "root" ; \x0d\x0a String password = "root" ; \x0d\x0a try{ \x0d\x0a Connection con = \x0d\x0a DriverManager.getConnection(url , username , password ) ; \x0d\x0a }catch(SQLException se){ \x0d\x0a System.out.println("数据库连接失败!"); \x0d\x0a se.printStackTrace() ; \x0d\x0a } \x0d\x0a 4、创建一个Statement \x0d\x0a •要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3 \x0d\x0a 种类型: \x0d\x0a 1、执行静态SQL语句。通常通过Statement实例实现。 \x0d\x0a 2、执行动态SQL语句。通常通过PreparedStatement实例实现。 \x0d\x0a 3、执行数据库存储过程。通常通过CallableStatement实例实现。 \x0d\x0a 具体的实现方式: \x0d\x0a Statement stmt = con.createStatement() ; \x0d\x0a PreparedStatement pstmt = con.prepareStatement(sql) ; \x0d\x0a CallableStatement cstmt = \x0d\x0a con.prepareCall("{CALL demoSp(? , ?)}") ; \x0d\x0a 5、执行SQL语句 \x0d\x0a Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate \x0d\x0a 和execute \x0d\x0a 1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句 \x0d\x0a ,返回一个结果集(ResultSet)对象。 \x0d\x0a 2、int executeUpdate(String sqlString):用于执行INSERT、UPDATE或 \x0d\x0a DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等 \x0d\x0a 3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的 \x0d\x0a 语句。 \x0d\x0a 具体实现的代码: \x0d\x0a ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; \x0d\x0a int rows = stmt.executeUpdate("INSERT INTO ...") ; \x0d\x0a boolean flag = stmt.execute(String sql) ; \x0d\x0a 6、处理结果 \x0d\x0a 两种情况: \x0d\x0a 1、执行更新返回的是本次操作影响到的记录数。 \x0d\x0a 2、执行查询返回的结果是一个ResultSet对象。 \x0d\x0a • ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get方法提供了对这些 \x0d\x0a 行中数据的访问。 \x0d\x0a • 使用结果集(ResultSet)对象的访问方法获取数据: \x0d\x0a while(rs.next()){ \x0d\x0a String name = rs.getString("name") ; \x0d\x0a String pass = rs.getString(1) ; // 此方法比较高效 \x0d\x0a } \x0d\x0a (列是从左到右编号的,并且从列1开始) \x0d\x0a 7、关闭JDBC对象 \x0d\x0a 操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声 \x0d\x0a 明顺序相反: \x0d\x0a 1、关闭记录集 \x0d\x0a 2、关闭声明 \x0d\x0a 3、关闭连接对象 \x0d\x0a if(rs != null){ // 关闭记录集 \x0d\x0a try{ \x0d\x0a rs.close() ; \x0d\x0a }catch(SQLException e){ \x0d\x0a e.printStackTrace() ; \x0d\x0a } \x0d\x0a } \x0d\x0a if(stmt != null){ // 关闭声明 \x0d\x0a try{ \x0d\x0a stmt.close() ; \x0d\x0a }catch(SQLException e){ \x0d\x0a e.printStackTrace() ; \x0d\x0a } \x0d\x0a } \x0d\x0a if(conn != null){ // 关闭连接对象 \x0d\x0a try{ \x0d\x0a conn.close() ; \x0d\x0a }catch(SQLException e){ \x0d\x0a e.printStackTrace() ; \x0d\x0a } \x0d\x0a }
Java中对数据库操作实例
可以以普通的jdbc连接的使用习惯来使用连接池。 数据库连接池在编写应用服务是经常需要用到的模块,太过频繁的连接数据库对服务性能来讲是一个瓶颈,使用缓冲池技术可以来消除这个瓶颈。我们可以在互联网上找到很多关于数据库连接池的源程序,但是都发现这样一个共同的问题:这些连接池的实现方法都不同程度地增加了与使用者之间的耦合度。很多的连接池都要求用户通过其规定的方法获取数据库的连接,这一点我们可以理解,毕竟目前所有的应用服务器取数据库连接的方式都是这种方式实现的。但是另外一个共同的问题是,它们同时不允许使用者显式的调用Connection.close()方法,而需要用其规定的一个方法来关闭连接。这种做法有两个缺点:第一:改变了用户使用习惯,增加了用户的使用难度。首先我们来看看一个正常的数据库操作过程:int executeSQL(String sql) throws SQLExceptionfinallycatch(Exception e)catch(Exception e)return res;}使用者在用完数据库连接后通常是直接调用连接的方法close来释放数据库资源,如果用我们前面提到的连接池的实现方法,那语句conn.close()将被某些特定的语句所替代。第二:使连接池无法对之中的所有连接进行独占控制。由于连接池不允许用户直接调用连接的close方法,一旦使用者在使用的过程中由于习惯问题直接关闭了数据库连接,那么连接池将无法正常维护所有连接的状态,考虑连接池和应用由不同开发人员实现时这种问题更容易出现。综合上面提到的两个问题,我们来讨论一下如何解决这两个要命的问题。首先我们先设身处地的考虑一下用户是想怎么样来使用这个数据库连接池的。用户可以通过特定的方法来获取数据库的连接,同时这个连接的类型应该是标准的java.sql.Connection。用户在获取到这个数据库连接后可以对这个连接进行任意的操作,包括关闭连接等。通过对用户使用的描述,怎样可以接管Connection.close方法就成了我们这篇文章的主题。为了接管数据库连接的close方法,我们应该有一种类似于钩子的机制。例如在Windows编程中我们可以利用Hook API来实现对某个Windows API的接管。在JAVA中同样也有这样一个机制。JAVA提供了一个Proxy类和一个InvocationHandler,这两个类都在java.lang.reflect包中。我们先来看看SUN公司提供的文档是怎么描述这两个类的。public interface InvocationHandlerInvocationHandler is the interface implemented by the invocation handler of a proxy instance. Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.SUN的API文档中关于Proxy的描述很多,这里就不罗列出来。通过文档对接口InvocationHandler的描述我们可以看到当调用一个Proxy实例的方法时会触发Invocationhanlder的invoke方法。从JAVA的文档中我们也同时了解到这种动态代理机制只能接管接口的方法,而对一般的类无效,考虑到java.sql.Connection本身也是一个接口由此就找到了解决如何接管close方法的出路。首先,我们先定义一个数据库连接池参数的类,定义了数据库的JDBC驱动程序类名,连接的URL以及用户名口令等等一些信息,该类是用于初始化连接池的参数,具体定义如下:public class ConnectionParam implements Serializable /** * 从连接池工厂中获取指定名称对应的连接池
java连接数据库的代码
package mysql;
import java.sql.*;
/**
* @author xys
*/
public class ConnectMysql {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "mysqluser";
String password = "password";
String driverClass = "com.mysql.cj.jdbc.Driver";
Connection connection = null;
Class.forName(driverClass);
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("数据库连接成功");
} else {
System.out.println("数据库连接失败");
connection.close();
}
return connection;
}
public void getResult() throws ClassNotFoundException, SQLException {
// 实例化 Statement 对象
Statement statement = getConnection().createStatement();
// 要执行的 Mysql 数据库操作语句(增、删、改、查)
String sql = "";
// 展开结果集数据库
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 通过字段检索
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// 输出数据
System.out.println("ID : " +id);
System.out.println("name :" + name);
}
// 完成后需要依次关闭
resultSet.close();
statement.close();
getConnection().close();
}
}
关于java数据库操作语句和javasql语句的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。