JDBC连接MySQL.docx

上传人:b****1 文档编号:14708972 上传时间:2023-06-26 格式:DOCX 页数:18 大小:22.65KB
下载 相关 举报
JDBC连接MySQL.docx_第1页
第1页 / 共18页
JDBC连接MySQL.docx_第2页
第2页 / 共18页
JDBC连接MySQL.docx_第3页
第3页 / 共18页
JDBC连接MySQL.docx_第4页
第4页 / 共18页
JDBC连接MySQL.docx_第5页
第5页 / 共18页
JDBC连接MySQL.docx_第6页
第6页 / 共18页
JDBC连接MySQL.docx_第7页
第7页 / 共18页
JDBC连接MySQL.docx_第8页
第8页 / 共18页
JDBC连接MySQL.docx_第9页
第9页 / 共18页
JDBC连接MySQL.docx_第10页
第10页 / 共18页
JDBC连接MySQL.docx_第11页
第11页 / 共18页
JDBC连接MySQL.docx_第12页
第12页 / 共18页
JDBC连接MySQL.docx_第13页
第13页 / 共18页
JDBC连接MySQL.docx_第14页
第14页 / 共18页
JDBC连接MySQL.docx_第15页
第15页 / 共18页
JDBC连接MySQL.docx_第16页
第16页 / 共18页
JDBC连接MySQL.docx_第17页
第17页 / 共18页
JDBC连接MySQL.docx_第18页
第18页 / 共18页
亲,该文档总共18页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

JDBC连接MySQL.docx

《JDBC连接MySQL.docx》由会员分享,可在线阅读,更多相关《JDBC连接MySQL.docx(18页珍藏版)》请在冰点文库上搜索。

JDBC连接MySQL.docx

JDBC连接MySQL

JDBC连接MySQL经典方案

最近在学习数据库开发的一些实例,这里浅谈一下用JDBC连接数据库MySQL(当然也可以连接SQLSever或Oracle了,只是我更喜欢开源软件,同时也更简单)。

 

首先正确安装好MySQL,建立好数据库studentinfo

mysql>createdatabasestudentinfo;

 

然后编写java代码,ConnectToMySQL.java

importjava.sql.*;

publicclassConnectToMySQL{

 publicstaticConnectiongetConnection()throwsSQLException,

 java.lang.ClassNotFoundException{

 Stringurl="jdbc:

mysql:

//localhost:

3306/studentinfo";

 Class.forName("com.mysql.jdbc.Driver");

 StringuserName="root";

 Stringpassword="";

 Connectioncon=DriverManager.getConnection(url,userName,password);

 returncon;

 }

 publicstaticvoidmain(String[]args){

  try{

   Connectioncon=getConnection();

   Statementsql=con.createStatement();

   sql.execute("droptableifexistsstudent");

   sql.execute("createtablestudent(idintnotnullauto_increment,namevarchar(20)notnulldefault'name',mathintnotnulldefault60,primarykey(id));");

   sql.execute("insertstudentvalues(1,'AAA','99')");

   sql.execute("insertstudentvalues(2,'BBB','77')");

   sql.execute("insertstudentvalues(3,'CCC','65')");

   Stringquery="select*fromstudent";

   ResultSetresult=sql.executeQuery(query);

   System.out.println("Student表数据如下:

");

   System.out.println("---------------------------------");

   System.out.println("学号"+" "+"姓名"+" "+"数学成绩");

   System.out.println("---------------------------------");

   intnumber;

   Stringname;

   Stringmath;

   while(result.next()){

   number=result.getInt("id");

   name=result.getString("name");

   math=result.getString("math");

   System.out.println(number+" "+name+" "+math);

   }

   sql.close();

   con.close();

   

  }catch(java.lang.ClassNotFoundExceptione){

   System.err.println("ClassNotFoundException:

"+e.getMessage());

  }catch(SQLExceptionex){

   System.err.println("SQLException:

"+ex.getMessage());

  }

 }

}

要注意的是使用MySQL数据库,需要用到对应的JDBC驱动程序mysql-connector-java-5.0.3

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.SQLException;

importjava.sql.ResultSet;

importjava.sql.Statement;

importjava.sql.*;

 

publicclassBaseConnection{

 privateConnectioncon=null;  

 protectedConnectiongetCon(){

   ResultSetrs=null;

   Statementstmt=null;

  try{

   Class.forName("org.gjt.mm.mysql.Driver");

   Stringurl="jdbc:

mysql:

//192.168.0.10/数据库名?

user=USR&password=PWD";

    conn=DriverManager.getConnection(url);  

   stmt=conn.createStatement();

}catch(ClassNotFoundExceptione){

   e.printStackTrace();

  }catch(SQLExceptione){

   e.printStackTrace();

  }       

  returncon;

 }

}

1.把 mysql-connector-java-5.0.3-bin.jar放到%JAVA_HOME%\jre\lib\ext下

2.访问类:

packagemysqldb;

importjava.sql.*;

publicclassMysqlCon{

 

 privatestaticStringDriverName="org.gjt.mm.mysql.Driver";

 privateStringdbURL="jdbc:

mysql:

//localhost/test";

 privateStringdbuser="root";

 privateStringdbpassword="";

 privateConnectionconn;

 privateStatementstmt;

 privateResultSetrs;

 publicMysqlCon(){

  try{

   Class.forName(DriverName).newInstance();

   conn=DriverManager.getConnection(dbURL,dbuser,dbpassword);

   stmt=conn.createStatement();

   Stringsql="select*fromworker";

   rs=stmt.executeQuery(sql);

   while(rs.next()){

    System.out.println(rs.getString

(1));

   }

  }catch(InstantiationExceptione){

   //TODO自动生成catch块

   e.printStackTrace();

  }catch(IllegalAccessExceptione){

   //TODO自动生成catch块

   e.printStackTrace();

  }catch(ClassNotFoundExceptione){

   //TODO自动生成catch块

   e.printStackTrace();

  }catch(SQLExceptione){

   //TODO自动生成catch块

   e.printStackTrace();

  }

  

 }

}

 

packageinterphase;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.util.Vector;

importjavax.swing.JFrame;

importjavax.swing.JPanel;

importjavax.swing.JScrollPane;

importjavax.swing.JTable;

importjavax.swing.table.AbstractTableModel;

importmysqldb.MysqlCon;

publicclassShowRS{

 privateAbstractTableModelatm;

 privateJTablejtable;

 privateVectorvector;

 privateJScrollPanejsp;

 privateStringtitle[]={"职工号","职工名","性别","出生日期","工资"};

 privateMysqlConmysqlcon;

 privateJFrameframe;

 

 publicShowRS(){

  vector=newVector();

  atm=newAbstractTableModel(){

   publicintgetColumnCount(){

    returntitle.length;

   }

   publicintgetRowCount(){

    returnvector.size();

   }

   publicObjectgetValueAt(introwIndex,intcolumnIndex){

    if(!

vector.isEmpty())

     return((Vector)vector.elementAt(rowIndex)).elementAt(columnIndex);

    else

     returnnull;

   }

   //取得单元格中的属性值

   publicStringgetColumnName(intcolumnIndex){

    returntitle[columnIndex];

   }

   //数据模型不可编辑,该方法设置为空

   publicvoidsetValueAt(){}

   //取得列所属对象类

   publicClassgetCoumnClass(intc){

    returngetValueAt(0,c).getClass();

   }

   //设置单元格不可编辑,为缺省实现

   publicbooleanisCellEditable(introw,intcolumn){

    returnfalse;

   }};

   jtable=newJTable(atm);

   jtable.setToolTipText("显示全部查询结果");

   jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

   jtable.setCellSelectionEnabled(false);

   jtable.setShowVerticalLines(true);

   jtable.setShowHorizontalLines(true);

   jsp=newJScrollPane(jtable);

   mysqlcon=newMysqlCon();

   vector.removeAllElements();

   atm.fireTableDataChanged();

   try{

    ResultSetrs=mysqlcon.getResultSet();

    while(rs.next()){

     Vectorrec_vector=newVector();

     rec_vector.addElement(rs.getString

(1));

     rec_vector.addElement(rs.getString

(2));

     rec_vector.addElement(rs.getString(3));

     rec_vector.addElement(rs.getDate(4));

     rec_vector.addElement(newFloat(rs.getFloat(5)));

     vector.addElement(rec_vector);

    }

   }catch(SQLExceptione){

    //TODO自动生成catch块

    e.printStackTrace();

   }

   atm.fireTableDataChanged();

   frame=newJFrame();

   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   frame.add(jsp);

   frame.setSize(400,300);

   frame.setVisible(true);

 } 

}

教程由JAVA中文网整理校对发布(javaweb.cc)

JDBC连接MySQL

加载及注册JDBC驱动程序

Class.forName("com.mysql.jdbc.Driver");

Class.forName("com.mysql.jdbc.Driver").newInstance();

JDBCURL定义驱动程序与数据源之间的连接

标准语法:

:

:

MySQL的JDBCURL格式:

jdbc:

mysql//[hostname][:

port]/[dbname][?

param1=value1][¶m2=value2]….

示例:

jdbc:

mysql:

//localhost:

3306/sample_db?

user=root&password=your_password

常见参数:

user用户名

password密码

autoReconnect联机失败,是否重新联机(true/false)

maxReconnect尝试重新联机次数

initialTimeout尝试重新联机间隔

maxRows传回最大行数

useUnicode是否使用Unicode字体编码(true/false)

characterEncoding何种编码(GB2312/UTF-8/…)

relaxAutocommit是否自动提交(true/false)

capitalizeTypeNames数据定义的名称以大写表示

建立连接对象

Stringurl="jdbc:

mysql:

//localhost:

3306/sample_db?

user=root&password=your_password";

Connectioncon=DriverManager.getConnection(url);

建立SQL陈述式对象(StatementObject)

Statementstmt=con.createStatement();

执行SQL语句

executeQuery()

Stringquery="select*fromtest";

ResultSetrs=stmt.executeQuery(query);

结果集ResultSet

while(rs.next())

{rs.getString

(1);rs.getInt

(2);}

executeUpdate()

Stringupd="insertintotest(id,name)values(1001,xuzhaori)";

intcon=stmt.executeUpdate(upd);

execute()

示例:

try{

}

catch(SQLExceptionsqle)

{}

finally

{}

Java类型和SQL类型技术手册P421

PreparedStatement(预编语句)

PreparedStatementstmt=conn.prepareStatement("insertintotest(id,name)values(?

?

)");

stmt.setInt(1,id);

stmt.setString(2,name);

注:

一旦设定语句的参数值后,就可以多次执行改语句,直到调用clearParameters()方法将他清除为止

CallableStatement(预储程序)技术手册P430

JDBC2.0使用

ResultSet对象中的光标上下自由移动

Statementstmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

ResultSetrs=stmt.executeQuery("select*fromtest");

publicStatementcreateStatement(intresultSetType,intresultSetConcuttency)throwsSQLException

resultSetType

TYPE_FORWARD_ONLY只能使用next()方法。

TYPE_SCROLL_SENSITIVE可以上下移动,可以取得改变后的值。

TYPE_SCROLL_INSENSITIVE可以上下移动。

resultSetConcuttency

CONCUR_READ_ONLY只读

CONCUR_UPDATABLEResultSet对象可以执行数据库的新增、修改、和移除

直接使用ResultSet对象执行更新数据

新增数据

Statementstmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE);

ResultSetuprs=stmt.executeQuery("select*fromtest");

uprs.moveToInsertRow();

uprs.updateInt(1,1001);

uprs.updateString(2,"许召日");

uprs.insertRow;

更新数据

Statementstmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE);

ResultSetuprs=stmt.executeQuery("select*fromtest");

uprs.last();

uprs.updateString("name","xuzhaori");

uprs.updateRow;

删除数据

Statementstmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_PUDATABLE);

ResultSetuprs=stmt.executeQuery("select*fromtest");

uprs.absolute(4);

uprs.deleteRow();

批处理

con.setAutoCommit(false);关闭自动认可模式

Statementstmt=con.createStatement();

int[]rows;

stmt.addBatch("insertintotestvalues(1001,xuzhaori)");

stmt.addBatch("insertintotestvalues(1002,xuyalin)");

rows=stmt.executeBatch();

mit();没有任何错误,执行批处理stmt.executeBatch();

JNDI-数据源(DataSource)与连接池(ConnectionPool)

Tomcat的JDBC数据源设置技术手册P439

连接池工具-ProxoolVar0.8.3技术手册P446

设置web.xml

xmlversion="1.0"encoding="ISO-8859-1"?

>

--

xmlversion="1.0"encoding="GB2312"?

>-->

xmlns:

xsi="http:

//www.w3.org/2001/XMLSchema-instance"

xsi:

schemaLocation="

version="2.4">

….

ServletConfigurator

org.logicalcobwebs.proxool.configuration.ServletConfigurator

propertyFile

WEB-INF/classes/Proxool.properties

1

后端统计端口添加下列

Admin

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 人文社科 > 法律资料

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2