mysql与java的连接问题

首先下载安装mysql与elipse,具体的java连接代码如下所示。

package pcl;
import java.sql.*; 

public
class JDBCTest { public static void main(String[] args){ // 驱动程序名 String driver = "com.mysql.jdbc.Driver"; // URL指向要访问的数据库名university 3306是我的mysql提供的服务端口,university是我建立的数据库
String url = "jdbc:mysql://localhost:3306/university"; // MySQL配置时的用户名 String user ="root"; // MySQL配置时的密码 String password = "1234"; try {
// 加载驱动程序 Class.forName(driver); // 连续数据库 Connection conn = DriverManager.getConnection(url, user, password); if(!conn.isClosed()) System.out.println("Succeeded connecting to the Database!");
// stmt用来执行SQL语句 Statement stmt = conn.createStatement(); // 要执行的SQL语句 String sql = "select * from student"; // 结果集 ResultSet rs = stmt.executeQuery(sql); System.out.println("-----------------"); System.out.println("执行结果如下所示:"); System.out.println("-----------------"); System.out.println(" 学号" + "\t" + " 姓名"); System.out.println("-----------------"); String name = null; while(rs.next()) { // 选择sname这列数据 //name = rs.getString("sname"); // 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。 // 然后使用GB2312字符集解码指定的字节数组 //name = new String(name.getBytes("ISO-8859-1"),"GB2312"); // 输出结果 System.out.println(rs.getString("sno") + "\t" + rs.getString("sname")); } rs.close(); conn.close(); } catch(ClassNotFoundException e) { System.out.println("Sorry,can't find the Driver!"); e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } }

这里要注意几点:

 (1)下载mysql-connector-java-5.0.8,将其中的jar包导入eclipse的工程中

 (2)端口问题:要保证你的mysql的端口正确配置了,可以在mysql的shell中用    show variables like 'port';      查看端口;

若是出现端口为0的情况,可能是因为你的安装时没有配置默认端口,可以找到mysql安装路径下的\bin\MySQLInstanceConfig开始图形化重新配置。

网上也流传了其他几种修改port的方法,比如直接修改my.ini / my.cnf(通常直接改是不行的,可以先复制出来,再粘贴回去)。修改之后如下:

[client]

port=3306

[mysql]

default-character-set=utf8

# SERVER SECTION # ---------------------------------------------------------------------- # # The following options will be read by the MySQL Server. Make sure that # you have installed the server correctly (see above) so it reads this # file. # [mysqld]

# The TCP/IP Port the MySQL Server will listen on

port=3306

(3)确保你的mysql服务已经打开

................................................

 

posted @ 2014-05-30 19:14  hedgehog小子  阅读(151)  评论(0)    收藏  举报