用JAVA实现数据库中信息的添加

	//00,提升变量作用范围
	Connection connection=null;
	Statement statement=null;
	try {
		Class.forName("com.mysql.jdbc.Driver");
		connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");	//jdbc类似于http,mysql是数据库管理系统,127.0.0.1是本机IP,3306是端口号,test是数据库,第一个root是用户名,第二个root密码。
		statement=connection.createStatement();
		for(int i=0;i<50;i++) {	//向数据库中添加50行数据。
			String id=UUID.randomUUID().toString();
			System.out.println(id);		//UUID产生的id。
			
			String sql="insert into user_info (id,user_name,password) values('"+id+"','"+i+"','"+i+"')";		//'"+id+"'中单引号是因为id,user_name,password要插入的是char类型的数,双引号是开口?,加号是连接。定义出添加指令
			int affect=statement.executeUpdate(sql);	//在statement窗口调用executeUpdate(sql);方法执行指令,返回一个受影响的行数,因为每循环一次,执行一次,每次受影响的都是1行。
			System.out.println(sql);	
			System.out.println(affect);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}finally {	//6,释放资源过程:先关掉窗口,再关掉连接,一般顺序不能改变
		try {
			if(statement!=null) {,	//02,加if是防止出现空指针异常,如果Class.forName("com.mysql.jdbc.Driver");此语句出现非检查时错误,try中的其他语句会终止执行。不加if时statement一定为null,会执行关闭资源的语句,因为根本没有启动所以会出错。加if后出现null不执行语句,不会关闭。
				statement.close(); //01,单独的此语句会出错,需要捕捉异常
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		try {
			if(connection!=null) {
			connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

说明:

executeUpdate()用于执行update,insert,delete语句,返回一个整数,整数代表此次操作所影响的表		的行数。
// 插入语句
 String sql = "insert into use_info (id,user_name,password) values ('id','user_name','password')";
// 修改语句
String sql = "update student set name='名字',address='地址',mobile='手机号' where id='11'";
//删除语句
	String sql = "delete from student where id='id'";
不同的sql语句执行不同的操作。

finally中的语句不能写成下边的形式:因为如果出现statement异常,connection连接将不会关闭

finally {
		try {
		if (statement!=null) {
			statement.close();
		}
		if (connection!=null) {
			connection.close();
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
}

猜你喜欢

转载自blog.csdn.net/YXX_decsdn/article/details/89638545