Ⅰ 在java中怎么对数据库的数据进行操作
首先,你要先有一个数据库。
然后下在你的数据库对应的JDBC驱动。
将驱动的jar包放到项目的classpath。
然后就可以编写程序来连接数据库,并进行保存和查询操作了。
保存数据通过执行INSERT INTO语句
查询数据通过SELECT语句
总之,如果是新手,需要了解的只是挺多的。先看看JDBC的内容吧。
如果不想了解太多细节,可以直接使用Hibernate框架,不过第一次用可能会觉得配置比较繁琐。
Ⅱ 如何用Java实现数据库查询
import java.sql.*;
public class MSSQLText
{
public static void main(String args[])
{
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind";
String user="sa";//这里替换成你自已的数据库用户名
String password="sa";//这里替换成你自已的数据库用户密码
String sqlStr="select CustomerID, CompanyName, ContactName from Customers";
try
{ //这里的异常处理语句是必需的.否则不能通过编译!
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("类实例化成功!");
Connection con = DriverManager.getConnection(url,user,password);
System.out.println("创建连接对像成功!");
Statement st = con.createStatement();
System.out.println("创建Statement成功!");
ResultSet rs = st.executeQuery(sqlStr);
System.out.println("操作数据表成功!");
System.out.println("----------------!");
while(rs.next())
{
System.out.print(rs.getString("CustomerID") + " ");
System.out.print(rs.getString("CompanyName") + " ");
System.out.println(rs.getString("ContactName"));
}
rs.close();
st.close();
con.close();
}
catch(Exception err){
err.printStackTrace(System.out);
}
}
}
Ⅲ 在Java中如何对数据库中的数据进行操作
package com.;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.;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 List<News> selectAllNews(){
List<News> list=new ArrayList<News>();
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程序是怎么操作数据库的(高分悬赏)
Java 实现连接sql server 20002007-12-16 13:28:00.0
第一种:通过ODBC连接数据库
JAVA语言的跨平台的工作能力(Write Once ,Run Anywhere)、优秀的图像处理能力(我相信现在没有那种语言可以超过JAVA在网络上的图形处理能力)、网络通信功能、通过JDBC数据库访问技术等等,让我们谁都不可否认JAVA语言是SUN公司对于计算机界的一个巨大的贡献。笔者可以描述这样一个场景:有一天你上网完全可以不用IE 或者NETSCAPE,上网就像是玩游戏,你可以获得游戏那么精美的图像和互动的感觉,如果你玩过UO,也许你就知道那种感觉了,但是JAVA做成的东西一定会超过UO的,因为不单单是游戏,也不是单单是浏览器,如果你愿意(要你有钱,有时间,有优秀的JAVA人才)你可以把所有的这一切用Java完全集成出来!!!我不是夸大JAVA的功能,大家可以访问一下http://www.simchina.net的那个社区程序,你就能找到一种感觉了:相信我没有说什么假话 。好了,不说废话了,现在我向你介绍JAVA的数据库访问技术----JDBC数据库访问技术(你可千万不要搞成ODBC了哟!)。
JDBC技术事实上是一种能通过JAVA语言访问任何结构化数据库的应用程序接口(API)(Sun这样说的,我也不知道是不是真的),而且现在的JDBC 3.0据Sun说也能访问Execel等电子表格程序!
JDBC对于数据库的访问有四种方式,我们这里只是介绍两种:
第一种是通过ODBC做为“桥”(Bridge)对数据库访问,第二种是直接对数据库访问。
我们先来看看第一种JDBC<-->ODBC访问的流程:
JDBC Driver Mannager->JDBC<->ODBC桥->ODBC->数据库客户机驱动库->数据库服务器->返回查询结果,在这种访问中值的我们注意的是虽然JAVA是"Write Once ,Run Anywhere",但是如果通过这种访问的话,需要客户端必须设置ODBC和有相应的数据库客户机的驱动,当你看了下面的另外一个流程的时候或许你会想:明明下一种更方面,为什么还要有这个东西的产生!呵呵,因为,未必所有的数据库服务器提供商都提供下面的JDBC驱动程序(给JDBC访问提供相应的接口),所以就有了JDBC<->ODBC Bridge。
接着再让我们来看看第二种访问流程:
JDBC Driver Mannager->局部JDBC驱动->客户端数据库->数据库服务器->返回查询结果,这种访问事实上是转换JDBC调用为相应的数据库(Oracle, Sybase, Informix, DB2, 和其他的数据库数据库管理系统)的客户端API调用(这么说,不知道大家能不能懂,说简单点就好像ASP不是通过DSN对数据库访问而是通过OLEDB访问,说道这里我还是不知道大家能不能明白我的意思。哎呀,不要扔鸡蛋嘛!),这种方式的访问需要相应的数据库提供商提供相应的JDBC驱动程序,但是有一种好处,可以独立于odbc用于可以随处可Run的客户端的浏览器中的Applet程序。
我们下面将给大家一个通过JDBC-ODBC桥数据库访问的实例,但是在看下面的事例前我想问大家一次:JDK1.3装了吗?数据库驱动装了吗(我使用的是SQLserver)?你该没有使用Linux吧?虽然java支持Linux,但是老兄我可没有使用Linux哟(这同JAVA的Write Once ,Run Anywhere没有关系),由于使用了运行于Win下面的ODBC,我建议你看看这篇东西http://www.aspcn.com/showarticle.asp?id=112,否则你要是有了问题,出不了结果那岂不是要怪我(不过欲加之罪,何患无吃... ...),冤枉呀!
哎呀,说了这么多的废话,还是让我们来看看到底JDBC的调用吧!既然我们是通过odbc访问数据库,所以这个odbc是跑不了的,我们先来设置你的odbc:打开你的odbc数据源->选择系统dsn(Click加新的dsn-)->接下来输入选择数据库类型、输入dsn名:、选择服务器、连接数据库的方式、输入数据库的登陆用户和密码->测试连接,如果测试成功的话,那么你的dsn就建立好了,我的dsn名为Sqlserver.使用的是sqlserver7.0,以 “sa”登陆,密码为空。这些东西都是后面要用道的!
好了下面让我们来看程序代码: (该代码已经通过运行)
//###########################################################
//代码开始
//###########################################################
import java.sql.*;
//加载java数据连接包,java基本所有的数据库的调用的都在这个东西里面
public class InsertCoffees {
public static void main(String args[]) {
String url = "jdbc:odbc:sqlserver";
//取得连接的url名,注意sqlserver是dsn名
Connection con;
//实例化一个Connection对象
Statement stmt;
String query = "select * from col_link";
//选择所有的Col_link表中的数据输出
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//加载jdbc-odbc桥驱动
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
//加载jdbc-odbc桥错误
System.err.println(e.getMessage());
//其他错误
}
try {
con = DriverManager.getConnection(url, "sa", "");
//数据库连接
stmt = con.createStatement();
//Create 一个声明
stmt.executeUpdate("CREATE TABLE col_link (sitename varchar (20) NULL ,siteurl varchar (50) NULL) ");
//执行了一个sql语句生成了一个表col_link的表
stmt.executeUpdate("insert into col_link values('ASP中华网','http://www.aspcn.com')");
stmt.executeUpdate("insert into col_link values('永远到底有多远','http://xuankong.com')");
//执行一个insert into语句
stmt.executeUpdate("update col_link set siteurl='http://www.aspcn.com/xuankong/xuankongt.jpg' where siteurl='http://xuankong.com'");
//执行一个update语句,更新数据库
ResultSet rs = stmt.executeQuery(query);
//返回一个结果集
System.out.println("Col_link表中的数据如下(原始数据)");
//下面的语句使用了一个while循环打印出了col_link表中的所有的数据
System.out.println("站点名 "+" "+"站点地址");
System.out.println("---------------"+" "+"----------------");
while (rs.next()) {
String s = rs.getString("sitename");
String f = rs.getString("siteurl");
//取得数据库中的数据
System.out.println(s + " " + f);
/*String t = rs.getString(1);
String l = rs.getString(2);
System.out.println(t + " " + l);*/
/*jdbc提供了两种方法识别字段,一种是使用getXXX(注意这里的getXXX表示取不同类型字段的不同的方法)获得字段名,
第二种*是通过字段索引,在这里我把第二种方法注释了*/
/*你可以访问这个连接获得getxxx的用法:http://java.sun.com/docs/books/tutorial/jdbc/basics/_retrievingTable.html*/
}
stmt.close();
con.close();
//上面的语句关闭声明和连接
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
//显示数据库连接错误或者查询错误
}
}
}
//###########################################################
//代码结束
//###########################################################
在上面这个程序中我想你展示了如何使用JDBC-ODBC连接数据库,使用SQL语句生成一个表,使用SELECT、INSERT 、UPDATE语句取的、插入和更新一个表中的数据,如何通过字段名和字段索引访问数据库中的东东!我希望你能从上面的代码真正的学习到一些东西!
发挥你的想象力,设想一下JAVA到底,比如说可以通过数据库做一个不需要GUI(图形用户界面)的聊天室,呵呵,感觉起来就像在DOS环境下打字的聊天室!哈哈!
最后需要说的是笔者的调试上面程序的环境:WIN2000 , JDK1.3,MS SQLSERVER编辑软件:EDITPLUS 2.01a(这最后的东西可不是废话,虽然早就了一些专业的JAVA开发工具,但是笔者建议JAVA初学者使用文本软件开发JAVA程序)
第二种:直接用jdbc访问数据库
(1) 该实例已经运行通过
jsp连接Sql Server7.0/2000数据库
testsqlserver.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
//pubs为你的数据库的
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1);%>
您的第二个字段内容为:<%=rs.getString(2);%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
(2)java访问sqlserver服务器
第一步:安装jdbc
点击SQL Server for JDBC驱动程序安装程序setup.exe(可以到微软网站下载 http://msdn.microsoft.com/library/default.asp?rul=/downloads/list/sqlserver.asp下载)
第二步:设置系统变量classpath
假设SQL Server for JDBC 驱动程序安装在d:\jdbc\,则classpath应该设置如下:
classpath:=.;…;d:\jdbc\lib; d:\jdbc\lib\mssqlserver.jar; d:\jdbc\lib\msutil.jar; d:\jdbc\lib\msbase.jar;
注意:设置时要在最前面的点号和分号
第三步:编辑java程序并且运行
实例1如下:
//import com.microsoft.*;
//注意:在java与sql server 连接时不需要这个包,其他书上说这个包是必需的,这个问题有待进一步讨论
import java.sql.*;
import java.net.URL;
class insert
{
public static void main(String[] args)
{
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=northwind";
String query="select * from categories";
String query1="insert categories values(10,'Hanbao','Sweet')";
String query2="insert categories values(11,'Naicha','Coffee taste')";
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection con=DriverManager.getConnection(url,"sa","739555");
Statement stmt=con.createStatement();
stmt.executeUpdate(query1);
stmt.executeUpdate(query2);
stmt.close();
con.close();
}
catch(SQLException ex)
{
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
}
}
实例2如下:
//import com.microsoft.*;
//注意:在java与sql server 连接时不需要这个包,其他书上说这个包是必需的,这个问题有待进一步讨论
import java.sql.*;
import java.net.URL;
class java2sqlserver
{
public static void main(String[] args)
{
String url="jdbc:microsoft:sqlserver://localhost:1433;User=sa;Password=739555;DatabaseName=northwind";
String query="Select * From Categories";
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
//DriverManager.setLogStream(System.out);
Connection con=DriverManager.getConnection(url);
checkForWarning(con.getWarnings());
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(query);
dispResultSet(rs);
rs.close();
stmt.close();
con.close();
}
catch(SQLException ex)
{
System.out.println(ex.toString()+"----SQLException caught----");
while(ex!=null)
{
System.out.print("SQLState:"+ex.getSQLState());
System.out.print("Message:"+ex.getMessage());
System.out.print("Vendor:"+ex.getErrorCode());
ex=ex.getNextException();
System.out.println("");
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
}
private static boolean checkForWarning(SQLWarning warn)
{
boolean rc=false;
if(warn!=null)
{
System.out.println("----Warning----");
rc=true;
while(warn!=null)
{
System.out.print("SQLState:"+warn.getSQLState());
System.out.print("Message:"+warn.getMessage());
System.out.print("Vendor:"+warn.getErrorCode());
System.out.println("");
warn=warn.getNextWarning();
}
}
return rc;
}
private static void dispResultSet(ResultSet rs) throws SQLException
{
int i;
ResultSetMetaData rsmd=rs.getMetaData();
int numCols=rsmd.getColumnCount();
for(i=1;i<=numCols;i++)
{
if(i>1) System.out.print(", ");
System.out.print(rsmd.getColumnLabel(i));
}
System.out.println("");
boolean more=rs.next();
while(more)
{
for(i=1;i<numCols;i++)
{
if(i<1) System.out.print(", ");
System.out.println(rs.getString(i));
}
System.out.println("");
more=rs.next();
}
}
//System.out.println("Hello World!");
}
以上两个实例笔者已经通过运行!
Ⅳ 怎么使用JAVA连接数据库
1、首先我们先建好数据库,然后建立好程序的目录,因为是适用于初学者的,所以就建立一个简单的java project,如图。
Ⅵ java操作数据库的方式有哪些
JDBC是java数据库连接技术的简称,它提供了连接各种数据库的能力,这便使程序的可维护性和可扩展性大大的提高了.JDBC连接数据库常见的驱动方式有两种,一种是jdbc-odbc即桥连另外一种是纯java驱动.一般在做java开发的时候用第二种.so前一种我就不说了,纯java驱动方式连接步骤如下:
1.先把一个jdbc的jar包导入到项目(用MyEclipse开发)的lib中.
2.代码如下:
[c-sharp]view plain
importjava.sql.*;
/**
*连接数据库帮助类
*@authorAdministrator
*
*/
publicclassBaseDao{
="com.microsoft.sqlserver.jdbc.SQLServerDriver";
privatestaticfinalStringURL="jdbc:sqlserver://localhost:1433;DatabaseName=LibraryManageSystem";
="sa";
="sa";
/**
*连接数据库
*@return数据库连接对象
*@throwsClassNotFoundException
*@throwsSQLException
*/
publicConnectiongetConn()throwsClassNotFoundException,SQLException{
Class.forName(DRIVER);
Connectionconn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
returnconn;
}
/**
*释放资源
*@paramconn
*@parampstmt
*@paramrs
*@throwsSQLException
*/
publicvoidcloseAll(Connectionconn,PreparedStatementpstmt,ResultSetrs)throwsSQLException{
if(rs!=null){
rs.close();
}
if(pstmt!=null){
pstmt.close();
}
if(conn!=null){
conn.close();
}
}
/**
*执行SQL语句,可以进行增、删、改的操作
*@paramsql
*@return影响条数
*@throwsClassNotFoundException
*@throwsSQLException
*/
publicintexecuteSQL(Stringsql)throwsClassNotFoundException,SQLException{
Connectionconn=this.getConn();
PreparedStatementpstmt=conn.prepareStatement(sql);
intnumber=pstmt.executeUpdate();
this.closeAll(conn,pstmt,null);
returnnumber;
}
}
<Resourcename="jdbc/book"auth="Container"type="javax.sql.DataSource"
maxActive="100"maxIdle="20"maxWait="100"username="sa"password="sa"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;dataBaseName=book"
/>在config.xml文件中加入Resource标签,然后对数据库信息进行配置,当然这个数据库指的也是sqlserver有疑问可以qq757966892联系
packageweb.login.;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjavax.naming.Context;
importjavax.naming.InitialContext;
importjavax.sql.DataSource;
publicclassBaseDao{
protectedConnectionconn;
protectedPreparedStatementps;
protectedResultSetrs;
protectedStringsql;
publicConnectiongetConn(){
try{
Contextcontext=newInitialContext();
DataSourceds=(DataSource)context.lookup("java:comp/env/jdbc/user");
returnds.getConnection();
}catch(Exceptione){
e.printStackTrace();
returnnull;
}
}
publicvoidcloseAll(Connectionconn,PreparedStatementps,ResultSetrs){
try{
if(rs!=null){
rs.close();
rs=null;
}
if(ps!=null){
ps.close();
ps=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(Exceptione){
e.printStackTrace();
}
}
}
- 之后便可以建立业务类从而对数据库进行操作.
从代码知道首先吧jdbc驱动类装载java虚拟机中,即Class.forName(DRIVER);其次加载驱动并建立于数据库的连接Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);;然后发送SQL语句并的到结果集.之后处理结果,最后要关闭数据库的连接,释放资源.当然我说的这样连接数据库的方式使用的软件是sql和MyEclipse.
使用配置文件来连接数据库,当然这样的连接需要进行一些配置.其实这样的连接用专业术语来说就是连接池,连接池是负责分配管理和释放数据库连接.它允许用用程序重复使用一个现有的数据库连接不再重复建立连接.释放空闲时间超过最大空闲时间的数据库连接以避免因为没有释放数据库而引起的数据库遗漏.
连接池的创建分为以下几个步骤:1.配置context.xml文件 这个文件是服务器(指tomcat)的一个conf文件夹中,拷贝出来放入项目的lib文件夹中,具体配置如下:
[c-sharp]view plain
之后把数据库的驱动包,这里指的是sql2005的包放入服务器的lib中,这样以后如果在你自己的机子上都不用在重新导入这个包了.
然后就是从MyEclipse中取得这样的连接从而对数据库进行一些操作具体代码如下:
[c-sharp]view plain
Ⅶ JAVA如何实现数据库的批处理操作
批量数据进入数据库使用addBatch()和executeBatch()方法
PreparedStatement.addBatch(); ...... PreparedStatement.executeBatch();需要注意的是一次最多不要超过50条:1.因为插入的时候数据库已经锁定,然而若是一次性插入太多会造成其他业务的等待。2.会造成内存的溢出
举例:
PreparedStatement pst = (PreparedStatement) con.prepareStatement("insert into ***** values (?,'***')"); for (int i = 0; i < 10000; i++) { pst.setInt(1, i); // 把一个SQL命令加入命令列表 pst.addBatch(); } // 执行批量更新 pst.executeBatch(); // 语句执行完毕,提交本事务 con.commit();
Ⅷ java中使用JDBC完成数据库操作的基本步骤是什么
创建一个以JDBC连接数据库的程序,包含7个步骤:
1、加载JDBC驱动程序:
在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机),
这通过java.lang.Class类的静态方法forName(String className)实现。
例如:
try{
//加载MySql的驱动类
Class.forName("com.mysql.jdbc.Driver") ;
}catch(ClassNotFoundException e){
System.out.println("找不到驱动程序类 ,加载驱动失败!");
e.printStackTrace() ;
}
成功加载后,会将Driver类的实例注册到DriverManager类中。
2、提供JDBC连接的URL
•连接URL定义了连接数据库时的协议、子协议、数据源标识。
•书写形式:协议:子协议:数据源标识
协议:在JDBC中总是以jdbc开始
子协议:是桥连接的驱动程序或是数据库管理系统名称。
数据源标识:标记找到数据库来源的地址与连接端口。
例如:(MySql的连接URL)
jdbc:mysql:
//localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
useUnicode=true:表示使用Unicode字符集。如果characterEncoding设置为
gb2312或GBK,本参数必须设置为true 。characterEncoding=gbk:字符编码方式。
3、创建数据库的连接
•要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象,
该对象就代表一个数据库的连接。
•使用DriverManager的getConnectin(String url , String username ,
String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和
密码来获得。
例如:
//连接MySql数据库,用户名和密码都是root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
try{
Connection con =
DriverManager.getConnection(url , username , password ) ;
}catch(SQLException se){
System.out.println("数据库连接失败!");
se.printStackTrace() ;
}
4、创建一个Statement
•要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3
种类型:
1、执行静态SQL语句。通常通过Statement实例实现。
2、执行动态SQL语句。通常通过PreparedStatement实例实现。
3、执行数据库存储过程。通常通过CallableStatement实例实现。
具体的实现方式:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt =
con.prepareCall("{CALL demoSp(? , ?)}") ;
5、执行SQL语句
Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate
和execute
1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句
,返回一个结果集(ResultSet)对象。
2、int executeUpdate(String sqlString):用于执行INSERT、UPDATE或
DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等
3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的
语句。
具体实现的代码:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
int rows = stmt.executeUpdate("INSERT INTO ...") ;
boolean flag = stmt.execute(String sql) ;
6、处理结果
两种情况:
1、执行更新返回的是本次操作影响到的记录数。
2、执行查询返回的结果是一个ResultSet对象。
• ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get方法提供了对这些
行中数据的访问。
• 使用结果集(ResultSet)对象的访问方法获取数据:
while(rs.next()){
String name = rs.getString("name") ;
String pass = rs.getString(1) ; // 此方法比较高效
}
(列是从左到右编号的,并且从列1开始)
7、关闭JDBC对象
操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声
明顺序相反:
1、关闭记录集
2、关闭声明
3、关闭连接对象
if(rs != null){ // 关闭记录集
try{
rs.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(stmt != null){ // 关闭声明
try{
stmt.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(conn != null){ // 关闭连接对象
try{
conn.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
Ⅸ 怎样才能实现用Java对数据库中数据的操作
这个就看你的数据库设计了,比如说两个数据库,一个是存种类(酒,菜。。),一个是存种类里面的分类(白酒,啤酒。。),然后在项目中链接数据库进行操作