怎样用java连接mysql

如题所述

1、查找驱动程序
  MySQL目前提供的java驱动程序为Connection/J,可以从MySQL官方网站下载,并找到mysql-connector-java-3.0.15-ga-bin.jar文件,此驱动程序为纯java驱动程序,不需做其他配置。
  2、动态指定classpath
  如果需要执行时动态指定classpath,就在执行时采用-cp方式。否则将上面的.jar文件加入到classpath环境变量中。
  3、加载驱动程序
try{
 Class.forName(com.mysql.jdbc.Driver);
 System.out.println(Success loading Mysql Driver!);
}catch(Exception e)
{
 System.out.println(Error loading Mysql Driver!);
 e.printStackTrace();
}
  4、设置连接的url
jdbc:mysql://localhost/databasename[?pa=va][&pa=va]  
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-08-05
import java.sql.*;
public class Conn {
static Connection con;
static PreparedStatement sql;
static ResultSet res;
public Connection getConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");//需要自己下载
} catch (Exception e) {
e.printStackTrace();
}
try {
con= DriverManager.getConnection("jdbc:mysql://127.0.0.1/dbtest","root","123456"); //需要根据自己的修改
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Conn c=new Conn();
c.getConnection();
try {
sql= con.prepareStatement("select * from students");//选择数据表,后面的操作就是根据自己的特殊情况具体实现了
res=sql.executeQuery();
System.out.println("执行增删改前的数据:");
while (res.next()) {
String id=res.getString(1);
String name=res.getString("name");
String age=res.getString("age");
System.out.print("编号"+id+"\t");
System.out.print("姓名"+name+"\t");
System.out.println("年龄"+age+"\t");
}
sql=con.prepareStatement("insert into students values(?,?,?)");
sql.setString(1, "9");
sql.setString(2, "tf");
sql.setString(3, "33");
sql.executeUpdate();
sql=con.prepareStatement("update students set age=?where id='1'");
sql.setString(1, "55");
sql.executeUpdate();
Statement stmt=con.createStatement();
stmt.executeUpdate("delete from students where id='5'");
sql=con.prepareStatement("select * from students");
res=sql.executeQuery();
System.out.println("执行增删改后的数据:");
while (res.next()) {
String id=res.getString(1);
String name=res.getString("name");
String age=res.getString("age");
System.out.print("编号"+id+"\t");
System.out.print("姓名"+name+"\t");
System.out.println("年龄"+age+"\t");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}