package com;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBUtil {
/**
* 获取连接
* Connection:负责java程序跟数据库之间的连接
* Statement:执行sql语句
* ResultSet:负责存储执行了select语句结果集
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
Connection conn=getConnection();//获取跟数据库之间的连接
//创建Statement
Statement st=(Statement) conn.createStatement();
//执行sql语句
ResultSet rs=st.executeQuery("select * from emp");
while(rs.next()){//指针,指向下一行,有数据就返回true,没有则返回false
System.out.println("名字:"+rs.getString("name")+" 工资:"
+rs.getDouble("salary")+" 年龄:"+rs.getInt("age"));
}
//st.executeUpdate("insert into emp(name,salary,age) values('打雷',3600,20)");
//st.executeUpdate("delete from emp where id=0");
st.executeUpdate("update emp set name='老男孩' where id=2");
}
public static Connection getConnection() throws SQLException{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动,通过查看包可以找到,在com下的mysql下的jdbc下的Driver
//根据数据库的URL、用户名、密码连接数据库
conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","xiaowen");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
}
import java.sql.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBUtil {
/**
* 获取连接
* Connection:负责java程序跟数据库之间的连接
* Statement:执行sql语句
* ResultSet:负责存储执行了select语句结果集
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
Connection conn=getConnection();//获取跟数据库之间的连接
//创建Statement
Statement st=(Statement) conn.createStatement();
//执行sql语句
ResultSet rs=st.executeQuery("select * from emp");
while(rs.next()){//指针,指向下一行,有数据就返回true,没有则返回false
System.out.println("名字:"+rs.getString("name")+" 工资:"
+rs.getDouble("salary")+" 年龄:"+rs.getInt("age"));
}
//st.executeUpdate("insert into emp(name,salary,age) values('打雷',3600,20)");
//st.executeUpdate("delete from emp where id=0");
st.executeUpdate("update emp set name='老男孩' where id=2");
}
public static Connection getConnection() throws SQLException{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动,通过查看包可以找到,在com下的mysql下的jdbc下的Driver
//根据数据库的URL、用户名、密码连接数据库
conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","xiaowen");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
}