package javaHive2;
import java.sql.*;
/*
* java通过JDBC连接Mysql
* driveName ="com.mysql.jdbc.Driver"
* mysql端口默认为3306
* */
public class JavaMysql
{
private static String driveName ="com.mysql.jdbc.Driver";
public static void main(String[] args) throws SQLException
{
try
{
Class.forName(driveName);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
//sqoop是我的mysql中的一个数据库的名字
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/sqoop", "root", "test");
//mysql的username和password
if (!con.isClosed())
{
//测试是否连接成功
System.out.println("******************************************************");
System.out.println("Succeed connecting the mysql!");
System.out.println("******************************************************");
}
//创建一个Statement对象来将SQL语句发送到数据库
Statement stmt = con.createStatement();
String tableName = "employee";
String sql;
sql = "select * from employee";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("id" + "\t" + "name");
while (rs.next())
{
System.out.println(rs.getInt(1)+ "\t" + rs.getString(2));
}
System.out.println("******************************************************");
System.out.println("Succeed select the mysql table!");
}
}
输出结果为:
******************************************************
Succeed connect the mysql!
******************************************************
id name
101 zhangsan
102 lisi
103 wangwu
******************************************************
Succeed select the mysql table!