java mysql 的简单操作和连接

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

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


      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
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值