package cn.hncu.hello;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
public class DBHello {
@Test
public void test() throws Exception{
//1、加载连接器(驱动)
Class.forName("com.mysql.jdbc.Driver");
//2、建立连接
String url = "jdbc:mysql://127.0.0.1:3306/mydata?characterEncoding=utf8&useSSL=true";
String user = "root";
String password = "1234";
Connection con = DriverManager.getConnection(url, user, password);
//3、获取语句对象
Statement st = con.createStatement();
//4、对数据库表进行操作(增删改查)
//增::String sql = "INSERT INTO student(sno,sname,age,saddress) VALUES ('1012','小明',27,'益阳');";
//删::String sql = "DELETE FROM student WHERE sno = '1012';";
//改::String sql = "UPDATE student SET saddress = '中原' WHERE sname='杨过';";
//st.execute(sql);
//查::
String sql = "SELECT sno,sname,age,saddress FROM student;";
ResultSet rs = st.executeQuery(sql);
//之所以先next()一下,是因为数据表指针初始位置指向表头,而不是真正的数据
while(rs.next()){
String sno = rs.getString(1);
String sname = rs.getString(2);
int age = rs.getInt(3);
String saddress = rs.getString(4);
System.out.println(sno+","+sname+","+age+","+saddress);
}
}
}
简单版Java访问MySQL数据库
最新推荐文章于 2023-07-13 11:33:21 发布