ubuntu下eclipse连接mysql

提示:一定要保证电脑处于联网状态


我们要下载一个mysql-connector-java-5.0.8-bin.jar的东西(当然这个jar包的版本号和你的mysql版本号的关系不是非常大),放到你新建的dynamic project下的WebContent文件夹下的WEB-INF下的lib。让这个Web工程可以连接Mysql数据库。官网http://dev.mysql.com/downloads/connector/j/5.0.html


之后在project中的javaresources下的src文件夹新建一个classdb_test.java(详细内容见附件)

右键runas-> java application,看是否已经ok


假设ok的话,在webcontent文件夹下新建jspfile index.jsp(详细内容见附件)

右键project->runas ->run on server


应该能够在浏览器中看到你的内容了。假设报错,能够多尝试下几遍,可能是哪个环节出现了什么问题。

也可能是版本号不一致导致的,所以须要你多试几次。

内容可參考

http://www.2cto.com/os/201504/392308.html


db_test.java


importjava.sql.*;


publicclassdb_test{

publicstaticvoidmain(String[] srg){

try{

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

}catch(InstantiationException | IllegalAccessException

|ClassNotFoundException e) {

//TODOAuto-generated catch block

e.printStackTrace();

}

Connection conn = null;

try{

conn=DriverManager.getConnection("jdbc:mysql://localhost/mysql1","root","wtt561111");

}catch(SQLException e) {

//TODOAuto-generated catch block

e.printStackTrace();

}

Statement stmt = null;

try{

stmt= conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

}catch(SQLException e) {

//TODOAuto-generated catch block

e.printStackTrace();

}

String sql = "select* from student";


try{

ResultSetrs = stmt.executeQuery(sql);

while(rs.next()){

Stringsno=rs.getString(2);

System.out.println(sno);

}

}catch(SQLException e) {

//TODOAuto-generated catch block

e.printStackTrace();

}

}

}


index.jsp


<%@pagecontentType="text/html;charset=gb2312"%>

<%@pageimport="java.sql.*"%>

<html>

<body>

<%

try{

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

}catch(Exception e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

Connection conn = null;

try{

conn=DriverManager.getConnection("jdbc:mysql://localhost/mysql1","root","wtt561111");

}catch(SQLException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}


try{

if(conn.equals(null))

{out.println("nullerror");}

else{

//stmt= conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

Statementstmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

Stringsql = "select* from student";

ResultSetrs = stmt.executeQuery(sql);

while(rs.next()){

Stringsno=rs.getString(1);

out.println(sno);

}

}

}catch(SQLException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}


%>

</body>

</html>


原文地址:https://www.cnblogs.com/lxjshuju/p/7089882.html