· 9 years ago · Apr 03, 2017, 03:32 AM
1import java.sql.Connection;
2import java.sql.DriverManager;
3import java.sql.PreparedStatement;
4import java.sql.ResultSet;
5import java.util.Scanner;
6
7public class test {
8
9 public static void main(String args[]){
10 try{
11 createTable();
12 Scanner scan = new Scanner(System.in);
13 System.out.println("enter username");
14 String username = scan.nextLine();
15 if(createAccount(username)){
16 System.out.println("valid, account created");
17 }else{
18 System.out.println("username taken");
19 }
20 }catch(Exception e){
21 System.out.println(e.getMessage());
22 }
23 }
24
25 public static boolean createAccount(String username) throws Exception{
26 try{
27 Connection con = getConnection();
28 PreparedStatement statement = con.prepareStatement("SELECT * FROM users WHERE username='" + username + "';");
29 System.out.println(statement);
30 ResultSet result = statement.executeQuery();
31 if(result.next())
32 return false;
33 else{
34 insert(username, "test", "arjun", "narayan");
35 return true;
36 }
37 }catch(Exception e){
38 System.out.println(e.getMessage());
39 }
40 return false;
41 }
42
43 public static void insert(String username, String password, String fname, String lname) throws Exception{
44 try{
45 Connection con = getConnection();
46 PreparedStatement inserted = con.prepareStatement("INSERT INTO users(username, password, fname, lname) VALUES "
47 + "('"+ username +"', '"+ password + "', '" + fname + "', '" + lname + "')");
48 System.out.println(inserted.toString());
49 inserted.executeUpdate();
50 }catch(Exception e){
51 System.out.println(e.getMessage());
52 }finally{
53 System.out.println("insert worked");
54 }
55 }
56
57 public static void createTable() throws Exception{
58 try{
59 Connection con = getConnection();
60 PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS "
61 + "users(userId int NOT NULL AUTO_INCREMENT, username varchar(250), "
62 + "password varchar(250), fname varchar(250), lname varchar(250), PRIMARY KEY(userId))");
63 create.executeUpdate();
64
65 }catch(Exception e){
66 System.out.println(e.getMessage());
67 }finally{
68 System.out.println("table has been created or function complete.");
69 }
70 }
71
72 public static Connection getConnection() throws Exception{
73 try{
74 String driver = "com.mysql.jdbc.Driver";
75 //localhost (change IP if not)
76 String url = "jdbc:mysql://127.0.0.1:3306/test_schema";
77 String user = "root";
78 String password = "x5bhsmn7*";
79 Class.forName(driver);
80 Connection conn = DriverManager.getConnection(url, user, password);
81 System.out.println("connection successful.");
82 return conn;
83 }catch(Exception e){
84 System.out.println(e.getMessage());
85 }
86 return null;
87 }
88}