Java连接mysql(Eclipse中)
import java.sql.*;
public class mySqlConnection {
public void show()
{
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
Connection connection;
Statement stmt;
ResultSet res;
// 加载驱动程序以连接数据库
try {
Class.forName( "org.gjt.mm.mysql.Driver" );
connection = DriverManager.getConnection(url, username, password );
stmt = connection.createStatement();
res = stmt.executeQuery("select * from info");
//处理结果集
while (res.next())
{
String name = res.getString("name");
System.out.println(name);
}
res.close();
}
// 捕获加载驱动程序异常
catch ( ClassNotFoundException cnfex ) {
System.err.println("装载 JDBC/ODBC 驱动程序失败。");
cnfex.printStackTrace();
}
// 捕获连接数据库异常
catch ( SQLException sqlex ) {
System.err.println( "无法连接数据库" );
sqlex.printStackTrace();
}
}
public static void main(String[] args) {
mySqlConnection mysql = new mySqlConnection();
mysql.show();
}
}
public class mySqlConnection {
public void show()
{
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
Connection connection;
Statement stmt;
ResultSet res;
// 加载驱动程序以连接数据库
try {
Class.forName( "org.gjt.mm.mysql.Driver" );
connection = DriverManager.getConnection(url, username, password );
stmt = connection.createStatement();
res = stmt.executeQuery("select * from info");
//处理结果集
while (res.next())
{
String name = res.getString("name");
System.out.println(name);
}
res.close();
}
// 捕获加载驱动程序异常
catch ( ClassNotFoundException cnfex ) {
System.err.println("装载 JDBC/ODBC 驱动程序失败。");
cnfex.printStackTrace();
}
// 捕获连接数据库异常
catch ( SQLException sqlex ) {
System.err.println( "无法连接数据库" );
sqlex.printStackTrace();
}
}
public static void main(String[] args) {
mySqlConnection mysql = new mySqlConnection();
mysql.show();
}
}
相关说明:
1.运行程序前,请先下载JDBC驱动,本文使用版本为“mysql-connector-java-5.1.7-bin.jar” ,请将下载的驱动安放在jre安装路径的/lib/ext/目录下,例如:C:/Program Files/Java/jre6/lib/ext/
2.mysql-connector-java-5.1.7-bin.jar下载地址:http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.7.zip/from/http://mysql.mirror.tw/
3.本文在mysql的样本数据库“test”中建有表“info”,其中有个字段名称为”name“
α.Α.alpha β.Β.beta γ.Γ.gamma δ.Δ.delta
ε.Ε.epsilon ζ.Ζ.zeta η.Η.eta θ.Θ.theta
ι.Ι.iota κ.Κ.kappa λ.Λ.lambda μ.Μ.mu
ν.Ν.nu ξ.Ξ.xi ο.Ο.omicron π.Π.pi
ρ.Ρ.rho σ.Σ.sigma τ.Τ.tau υ.Υ.upsilon
ε.Ε.epsilon ζ.Ζ.zeta η.Η.eta θ.Θ.theta
ι.Ι.iota κ.Κ.kappa λ.Λ.lambda μ.Μ.mu
ν.Ν.nu ξ.Ξ.xi ο.Ο.omicron π.Π.pi
ρ.Ρ.rho σ.Σ.sigma τ.Τ.tau υ.Υ.upsilon