原始版
import java.sql.DriverManager;
import java.sql.Statement;
import com.mysql.jdbc.Connection;
class QueryTest {
public static void main(String[] args) {
// 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/student", "root", "123456");
// 获取数据库连接对象
Statement statement = conn.createStatement();
// 写sql语句
String sql = "insert into student (id,username) values (3,'LinDL')";
// 执行操作
statement.execute(sql);
// 关闭资源(注意顺序)
statement.close();
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
***
src下配置jdbc.properties
url=jdbc\:mysql\://localhost\:3306/student
user=root
password=123456
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtil {
private static String url="";
private static String user="";
private static String password="";
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn() throws Exception{
Properties properties=new Properties();
InputStream inputStream=JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(inputStream);
url=properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
Connection conn=DriverManager.getConnection(url, user, password);
return conn;
}
public static void closeAll(ResultSet rs,Connection conn,Statement stmt) throws Exception{
rs.close();
stmt.close();
conn.close();
}
}
import java.sql.ResultSet;
import java.sql.Statement;
class QueryTest {
public static void main(String[] args) {
// 注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
// Connection conn = (Connection) DriverManager.getConnection(
// "jdbc:mysql://localhost:3306/student", "root", "123456");
java.sql.Connection conn = JdbcUtil.getConn();
// 获取数据库连接对象
Statement statement = conn.createStatement();
// 写sql语句
//String sql1 = "insert into student (id,username) values (3,'LinDL')";
//// 执行操作
//statement.execute(sql1);
String sql2 = "select * from student";
ResultSet rs = statement.executeQuery(sql2);
while (rs.next()) {
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("username"));
}
// 关闭资源(注意顺序)
JdbcUtil.closeAll(rs, conn, statement);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。