以前没有怎么写博客,可能是自己太懒了吧。我想试着改变自己,让自己在工作中学习,在学习中分享。虽然只是小菜一个,但是我相信勤能补拙。
直接上正题吧,今天我写个很菜的代码,就是为了发片博客,高手请勿喷。
java 连接mysql数据库:
public class ConnectionUtils {
private ConnectionUtils(){}
private static ConnectionUtils instance=new ConnectionUtils();
private Connection conn;
public static ConnectionUtils getInstance(){
if(instance!=null){
return instance;
}else{
return null;
}
}
public Connection getConnection(){
if(conn == null){
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String pwd="123456";
try{
//加载驱动,这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立到MySQL的连接
conn = DriverManager.getConnection(url,user, pwd);
}catch(Exception e){
e.printStackTrace();
}
}
return conn;
}
public void closeConnection(){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
之后写过简单的创建数据表的方法吧:
private static void testCreateTable() {
Connection connection = ConnectionUtils.getInstance().getConnection();
try{
Statement sql = (Statement) connection.createStatement();
sql.execute("drop table if exists products");
sql.execute("create table products(id int null auto_increment,name varchar(20) not null default 'test',price int not null default 100,primary key(id));");
}catch(Exception e){
e.printStackTrace();
}
}
之后再写个最基础的增删改查代码,十分简单:
Connection conn = ConnectionUtils.getInstance().getConnection();
try{
Statement sql = (Statement) conn.createStatement();
//---------------查询-----------------
String selectStr="select * from users";
ResultSet result=sql.executeQuery(selectStr);
while(result.next()){
System.out.println(result.getInt("id")+" "+result.getString("username")+" "+result.getString("psw"));
}
//插入数据
String insertStr="insert users values(null,'sdfgs','dddd')";
sql.execute(insertStr);
//修改数据
String updateStr="update users set username='dd5555' where id=1";
sql.execute(updateStr);
//删除数据
String deleteStr="delete from users where username='dzh2'";
sql.execute(deleteStr);
}catch(Exception e){
e.printStackTrace();
}
学无止界,努力也是为了自己,伟大的it行业加油。