1.随机生成优惠码代码如下:
import java.util.Random; /** *功能:随机生成优惠码 *@author iamwiam * */ public class Activatedcode { public int ACTIVATEDCODENUM = 200; //生成的优惠码数量 Random random = new Random(); String candicatedCode = "abcedefghijklmnopqrstuvwxyz";//优惠码包含小写字母 candicatedCode+=candicatedCode.toUpperCase();//优惠码包含大写字母 candicatedCode+="1234567890";//优惠码包含阿拉伯数字 for(int i=0; i< ACTIVATEDCODENUM;i++){ String res =""; for(int j=0;j<8;j++){ res+=candicatedCode.charAt(random.nextInt(candicatedCode.lenght())); } System.out.println(res);//随机生成200个8位的优惠码 } }
2.将优惠码保存在数据库中
private static void insertToMySql(String res){ int n = 0; try{ Class.forName(“com.mysql.jdbc.Driver”); Connection connection = DriverMannager.getConnection(“jdbc:mysql://127.0.0.1/tb_act_code”,”zy”,”IamWiam”); String sql = “insert into checkNum(value) values(?)”; PreparedStatement ps = connection.prepareStatement(sql); ps.setObject(1,res); //占位符顺序从1开始,第一个参数是占位符的位置,第二个参数是占位符的值 n = ps.executeUpdate(); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); } }
3.整合
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Random; /** * 功能:随机生成优惠码 * @author iamwiam * */ public class Activatedcode { public static void main(String[] args) { final int ACTIVATEDCODENUM = 200; Random random = new Random(); String candicatedCode = "abcdefghijklmnopqrstuvwxyz"; candicatedCode+=candicatedCode.toUpperCase(); candicatedCode+="1234567890"; for(int i=0;i<ACTIVATEDCODENUM;i++){ String res =""; for(int j=0;j<8;j++){ res+=candicatedCode.charAt(random.nextInt(candicatedCode.length())); } // String pwd = Activatedcode.getMD5(Activatedcode.getMD5(res)); insertToMysql(res); } } private static void insertToMysql(String res) { int n=0; try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection( "jdbc:mysql://127.0.0.1/new2017", "zy", "IamWiam"); String sql = "insert into checkNum(value) values(?)"; PreparedStatement ps = connection.prepareStatement(sql); ps.setObject(1, res); n = ps.executeUpdate(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4.结果如下
相关推荐:
关于php接收ios客户端传过来的表情保存至mysql数据库
以上就是实例分享随机生成八位优惠码并保存至Mysql数据库的详细内容,更多请关注php中文网其它相关文章!
……