1、打开Eclipse,创建一个项目(my),
2、操作:右键点击my--->build Path--->add externalArchiver...选择jdbc驱动,点击确早弊定。
我的项目列表:
3.驱动已经导入,下陆销族面我们来写一个程序验证一下
import java.sql.*;
public class MysqlJdbc {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
//Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("Success loading Mysql Driver!");
}
catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try {
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","198876");
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
System.out.println("Success connect Mysql server!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
斗搜 //user 为你表的名称
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
}
}
}
4、点击运行程序:
Success loading Mysql Driver!
Success connect Mysql server!
huzhiheng
5、出现上面结果,说明你连接数据库成功
链接数据库其实很简单具体代码如下:
package db;
import java.sql.*;
public class DB {
private Connection con=null;
private Statement stmt=null;
private ResultSet rs=null;
public DB(){}
public Connection getConnection(){
String url="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
String dbuser="root";
String dbpass="sa";
String name="com.mysql.jdbc.Driver";
if(con==null){
try{
Class.forName(name).newInstance();
}catch(Exception e){
System.out.println(e);
}
try{
con=DriverManager.getConnection(url,dbuser,dbpass);
}catch(Exception e){}
}
return con;
}
public ResultSet exeQuery(String sql){
try{
con=getConnection();
if(con==null){
throw new Exception("没有可连接对象");
}
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
}catch(Exception e){}
return rs;
}
public boolean update(String sql){
boolean flag=true;
try{
con=getConnection();
if(con==null) throw new Exception("没有可连接对象");
stmt=con.createStatement();
stmt.executeUpdate(sql);
}catch(Exception e){
flag=false;
System.out.println("异常:"+e);
}
return flag;
}
public void close(){
try{
if(rs!=null)try{rs.close();}catch(Exception e){System.out.println("陆凳首rs"+e);}
try{stmt.close();}catch(Exception e){System.out.println("早数stmt"粗神+e);}
try{con.close();}catch(Exception e){System.out.println("con"+e);}
}catch(Exception e){}
}
}
Eclipse只是一个集成开发工具,可以差余慧开发很多种语言,不知道毁乎您打算使虚答用哪种语言进行编程。每种语言对应的连接数据库的方法都不太一样的。
楼上提供了java连接数据库的方法。不知道您是不是准备问java的。