java mysql 的简单操作和连接

来源:互联网 发布:剑网三数据导入要钱吗 编辑:程序博客网 时间:2024/05/22 09:48

       以前没有怎么写博客,可能是自己太懒了吧。我想试着改变自己,让自己在工作中学习,在学习中分享。虽然只是小菜一个,但是我相信勤能补拙。

       直接上正题吧,今天我写个很菜的代码,就是为了发片博客,高手请勿喷。


      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行业加油。

1 0
原创粉丝点击