- jdbc的简单练习并没有涉及到图形界面
- 数据库连接基本操作
package red;
import java.sql.*;
public class link {
static {
try {
String driverName="com.mysql.cj.jdbc.Driver";
Class.forName(driverName);
}catch (Exception e){
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection con=null;
try{
con= DriverManager.getConnection("jdbc:mysql://localhost/market"+"? serverTimezone=GMT%2B8","root","");
}catch (Exception e){
e.printStackTrace();
}
return con;
}
public static void close(Connection con, Statement statement, PreparedStatement preparedStatement, ResultSet rs){
try{
if(rs!=null) rs.close();
}catch (Exception e){
e.printStackTrace();
}
try{
if(con!=null) con.close();
}catch (Exception e){
e.printStackTrace();
}
try{
if(statement!=null)statement.close();
}catch (Exception e){
e.printStackTrace();
}
try{
if(preparedStatement !=null) preparedStatement.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
package red;
import java.sql.*;
import java.util.Scanner;
public class branchfirst {
Connection con;
PreparedStatement ptmt;
Statement statement;
ResultSet rs;
public Statement getStatement() {
return statement;
}
public Connection getCon() {
return con;
}
public ResultSet getRs() {
return rs;
}
public PreparedStatement getPreparedStatement() {
return ptmt;
}
public branchfirst(Connection con){
this.con=con;
try{
statement=con.createStatement();
}catch (Exception e){
e.printStackTrace();
}
}
public void createTable() throws SQLException{
try {
String sql="create table if not exists branch1(id int(10) primary KEY,operatingexpense int(150) ,governor varchar(20),contact int(50),address varchar(100))";
statement.executeUpdate(sql);
}catch (Exception e){
e.printStackTrace();
}
}
public void Insert()throws SQLException{
String sql;
System.out.println("请输入你想要添加的信息,结束输出时请按回车结束");
System.out.println("格式类似于:"+"\"insert into branch1 values(01,1000000,'小明',158123456789,'重庆市江北区')\"");
do{
Scanner scanner=new Scanner(System.in);
sql=scanner.nextLine();
if(!sql.equals(""))
statement.executeUpdate(sql);
}while(!sql.equals(""));
}
public void Select() throws SQLException{
String sql="select id,operatingexpense,governor,contact,address from branch1";
rs=statement.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
int oe=rs.getInt("operatingexpense");
String g=rs.getString("governor");
int c=rs.getInt("contact");
String ad=rs.getString("address");
System.out.println("--|"+id+"\t"+oe+"\t"+g+"\t"+c+"\t"+ad+"\t");
}
}
public void Delect() throws SQLExcepti