怎样用java连接mysql

2024-11-24 00:11:03
推荐回答(2个)
回答1:

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();
}
}
}

回答2:

import java.sql.*; public class JDBCTest { public static void main(String[] args){

驱动程序名
String driver = "com.mysql.jdbc.Driver";

// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://127.0.0.1:3306/scutcs";

// MySQL配置时的用户名
String user = "root";

// Java连接MySQL配置时的密码

String password = "root";

try {
// 加载驱动程序

Class.forName(driver);

// 连续数据库
Connection conn = DriverManager.getConnection(url, user, password);

if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");

// statement用来执行SQL语句
Statement statement = conn.createStatement();

// 要执行的SQL语句
String sql = "select * from student";

结果集
ResultSet rs = statement.executeQuery(sql); System.out.println("-----------------"); System.out.println("执行结果如下所示:"); System.out.println("-----------------"); System.out.println(" 学号" + "\t" + " 姓名"); System.out.println("-----------------"); String name = null; while(rs.next()) {