package com.xasmall.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Demo1 {
public static final String url = "jdbc:mysql://127.0.0.1/user";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "root";
public static Connection conn=null;
public Demo1() throws ClassNotFoundException, SQLException {
Class.forName(name);
conn=DriverManager.getConnection(url,user,password);
}
//Statement
public void exe1() throws SQLException {
Statement con=conn.createStatement();
String sql="insert into student values('37932747','张元')";
// String id="16281137";
// String name="张元";
// String sql="insert into student values('"+id+"','"+name+"')";
con.execute(sql);
con.close();
}
//PreparedStatement
public void exe2() throws SQLException {
String sql="Select *from student";
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
System.out.println("id"+"--------"+"name");
while(rs.next()){
System.out.println(rs.getString(1)+"----"+rs.getString(2));
}
ps.close();
}
//占位符
public void exe3() throws SQLException {
String sql="insert into student(id,name) values(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setObject(1, "379181930");
ps.setObject(2, "原子");
ps.execute();
ps.close();
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Demo1 test1=new Demo1();
test1.exe1();
test1.exe2();
test1.exe3();
}
}
java数据库基础(mysql)1
最新推荐文章于 2023-05-10 15:52:44 发布