[操作系统]Java如何连接到MySQL数据库的
0 2016-05-01 15:00:15
下载:mysql-connector-java-5.1.38.tar.gz
http://dev.mysql.com/downloads/connector/j/
tar zxvfmysql-connector-java-5.1.38.tar.gz
解压后
zhousp@ubuntu:~/Downloads$cd ./mysql-connector-java-5.1.38/
zhousp@ubuntu:~/Downloads/mysql-connector-java-5.1.38$ls
build.
CHANGES docs README src
zhousp@ubuntu:~/Downloads/mysql-connector-java-5.1.38$sudo cp mysql-connector-java-5.1.38-bin.jar /home/tomcat/lib
[sudo] password forzhousp:
Add External JARs
代码:
importjava.sql.*;
publicclassJDBCTest {
publicstaticvoidmain(String[] args){
//驱动程序名
Stringdriver= "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名bookstore
Stringurl= "jdbc:mysql://127.0.0.1:3306/bookstore";
//MySQL配置时的用户名
Stringuser= "root";
//MySQL配置时的密码
Stringpassword= "password";
try{
//加载驱动程序
Class.forName(driver);
//连续数据库
Connectionconn= DriverManager.getConnection(url,user,password);
if(!conn.isClosed())
System.out.println("Succeededconnecting to the Database!");
//statement用来执行SQL语句
Statementstatement= conn.createStatement();
//要执行的SQL语句
Stringsql= "select* from books";
//结果集
ResultSetrs= statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------------------------------------");
System.out.println("ISBN"+ "\t"+ "author"+"\t"+ "bookname"+"\t"+ "bookname");
System.out.println("-----------------------------------------------");
Stringname= null;
while(rs.next()){
//选择ISBN这列数据
name= rs.getString("ISBN");
//System.out.println(name);
//首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
//然后使用GB2312字符集解码指定的字节数组
name= newString(name.getBytes("ISO-8859-1"),"GB2312");
//输出结果
System.out.println(name+ "\t"+ rs.getString("author")+ "\t"+ rs.getString("bookname")+ "\t"+ "\t"+ rs.getString("price"));
}
rs.close();
conn.close();
}catch(ClassNotFoundExceptione){
System.out.println("Sorry,can`tfind the Driver!");
e.printStackTrace();
}catch(SQLExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
}
}
输出:
Succeededconnecting to the Database!
-----------------
执行结果如下所示:
-----------------------------------------------
ISBNauthor bookname bookname
-----------------------------------------------
123456zhouspjava23.40
234567zhouspC++34.60
本文网址:http://www.shaoqun.com/a/217270.html
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。
JAVA
0