MyEclipse环境下java连接数据库小例子
package conn;
import java.sql.*;
public class TestMysql {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/Psychology","root","123456");
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from users");
while(rs.next())
{
int id=rs.getInt(1);
String username=rs.getString(2);
String password=rs.getString(3);
System.out.println("用户名:"+username+","+"密码:"+password);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs!=null){
rs.close();
rs=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(conn!=null){
conn.close();
conn=null;
}
}catch(Exception e1){
e1.printStackTrace();
}
}
}
}
注:要连接成功先要在项目中加载mysql的驱动:mysql-connector-java-3.1.12-bin.jar;(右击项目--Properties--Java Build Path--Libraries--Add External JARS... 选择要导入的jar包OK即可).