SlideShare a Scribd company logo
1 of 7
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>


     <form action="index.jsp" method="post">

       First Name: <input type="text" name="firstName"><br>
       Last Name: <input type="text" name="lastName"><br>
       Email Address: <input type="text" name="emailAddress"><br>



       <input type="submit" Value="Submit">
     </form>
  </body>
</html>
<%@pagecontentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*, business.User, javax.servlet.*, java.io.*, javax.servlet.http.*, java.sql.*,
java.util.*, util.SQLDBUtil" %>

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
  </head>
  <body>
    <h1>mySQL</h1>
    <%
    User user;
       try {
          String dbUrl = "jdbc:mysql://localhost:3306/murach";
          String username = "root";
          String password = "sesame";
          String query = "SELECT * FROM murach.user";
          String userName = "";
          SQLDBUtilutil = new SQLDBUtil();



           ArrayList<User> users = new ArrayList<User>();


           //insert a new record

util.insertUser(request.getParameter("firstName"),request.getParameter("lastName"),request.getParamet
er("emailAddress"));

           Connection conn = DriverManager.getConnection(dbUrl, username, password);
           PreparedStatementps = conn.prepareStatement(query);
           Statement statement = conn.createStatement();
           ResultSetrs = statement.executeQuery(query);
           while(rs.next())
           {

              user = new User(rs.getString(2),rs.getString(3),rs.getString(4));
              users.add(user);
              //userName = user.getFirstName();
           }
           rs.close();

     Iterator it = users.iterator();
     User tempUser;

     %>
     <table cellpadding="5" cellspacing="5" border =" 1">
     <%
     while(it.hasNext())
     {
tempUser = (User) it.next();


    %>
    <tr>

      <td>First Name:</td>
      <td><%= tempUser.getFirstName() %></td>
      <td> Last Name: </td>
      <td><%= tempUser.getLastName() %></td>
      <td> Email Address: </td>
      <td><%= tempUser.getEmailAddress() %></td>
    <br>
    </tr>

    <%
      }
    %>

    </table>

    <%

      } catch (SQLException e)

      {
          for (Throwable t : e)
        t.printStackTrace();
      } finally
      {

      }

     %>
  </body>
</html>
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package business;
/**
 *
 * @author tpersson
 */
public class User {

    String firstName, lastName, emailAddress;


    public User ()
    {
    }

    public User (String first, String last, String email)
    {
      firstName = first;
      lastName = last;
      emailAddress = email;

    }

    public String getFirstName()
    {
       return firstName;
    }
    public String getLastName()
    {
      return lastName;
    }
    public String getEmailAddress()
    {
          return emailAddress;
    }

}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;
importjava.sql.*;
import business.User;
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
/**
 *
 * @author tpersson
 */
public class SQLDBUtil{
    String dbUrl = "jdbc:mysql://localhost:3306/murach";
    String username = "root";
    String password = "sesame";
    String query = "";
    //connection objects
    Connection conn;
    PreparedStatementps;
    Statement statement;
    publicSQLDBUtil() {
    }
    public void insertUser(String first, String last, String email)
    {
       //query = "INSERT INTO murach.user('',first, last, email)";
       query = "INSERT into murach.user (FirstName,LastName,EmailAddress) values ('" + first + "','" +
last + "','" + email + "')";
       runQuery(query);
    }
    public void updateUser(String first, String last, String email)
    {


          if(doesExist(email))
          {
               query = "UPDATE murach.user SET FirstName ='"+ first
+"',LastName='"+last+"',EmailAddress='"+email2 +"' WHERE EmailAddress='" + email +"'";
               runQuery(query);
          }
          else
          {
              //out.printLine("No record with that email address");
          }
   }
private void connectDb()
{
   try {
       conn = DriverManager.getConnection(dbUrl, username, password);
   } catch (SQLException e)
   {
   } finally
   {
   }
}
private void runQuery(String q) {
   try {
       connectDb();
       PreparedStatementps = conn.prepareStatement(query);
       Statement statement = conn.createStatement();
       ps.executeUpdate();
       conn.close();

  } catch (SQLException e) {
  } finally {
  }
}
private booleandoesExist(String email)
{
   Boolean exists = false;
   ResultSetrsCheck;
   connectDb();
   query="SELECT * FROM murach.User WHERE EmailAddress='" + email + "'";
   try
   {

        ps = conn.prepareStatement(query);
        statement = conn.createStatement();
        rsCheck = statement.executeQuery(query);
        rsCheck.last();


        if(rsCheck.getRow()>0)
        {
            exists = true;
        }

  }
  catch(SQLException e)
  {

  }
  finally
  {
     return exists;

  }
}
}

More Related Content

What's hot

ABV_fastcontact
ABV_fastcontactABV_fastcontact
ABV_fastcontact
arjun rao
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
User controls
User controlsUser controls
User controls
aspnet123
 

What's hot (20)

jrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeusjrubykaigi2010-lt-rubeus
jrubykaigi2010-lt-rubeus
 
Idoc script beginner guide
Idoc script beginner guide Idoc script beginner guide
Idoc script beginner guide
 
ABV_fastcontact
ABV_fastcontactABV_fastcontact
ABV_fastcontact
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
apache tajo 연동 개발 후기
apache tajo 연동 개발 후기apache tajo 연동 개발 후기
apache tajo 연동 개발 후기
 
Intro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask MeetupIntro to Jinja2 Templates - San Francisco Flask Meetup
Intro to Jinja2 Templates - San Francisco Flask Meetup
 
Using web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworksUsing web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworks
 
Library Project Marcelo Salvador
Library Project Marcelo SalvadorLibrary Project Marcelo Salvador
Library Project Marcelo Salvador
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
 
5. CodeIgniter copy1
5. CodeIgniter copy15. CodeIgniter copy1
5. CodeIgniter copy1
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
14922 java script built (1)
14922 java script built (1)14922 java script built (1)
14922 java script built (1)
 
Web2py
Web2pyWeb2py
Web2py
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
User controls
User controlsUser controls
User controls
 

Viewers also liked

Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)
Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)
Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)
raperry6073
 
partiture editi ergys estrefi
partiture editi ergys estrefipartiture editi ergys estrefi
partiture editi ergys estrefi
Ergys Estrefi
 
Asia pacific tour... why not?
Asia pacific tour... why not?Asia pacific tour... why not?
Asia pacific tour... why not?
Kamnium
 
Jenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめ
Jenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめJenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめ
Jenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめ
atsushi_tmx
 
мотивация власти презентация григорьева
мотивация власти презентация григорьевамотивация власти презентация григорьева
мотивация власти презентация григорьева
Nick Grigoryev
 

Viewers also liked (13)

Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)
Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)
Advanced Safe Harbor 401(K) Plan Designs (For The Financial Advisor)
 
partiture editi ergys estrefi
partiture editi ergys estrefipartiture editi ergys estrefi
partiture editi ergys estrefi
 
Appnotech – Developing the future
Appnotech – Developing the futureAppnotech – Developing the future
Appnotech – Developing the future
 
partiture illyrian demo
partiture illyrian demopartiture illyrian demo
partiture illyrian demo
 
Asia pacific tour... why not?
Asia pacific tour... why not?Asia pacific tour... why not?
Asia pacific tour... why not?
 
Jenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめ
Jenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめJenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめ
Jenkins ユーザ・カンファレンス 2012 東京 S406-4/マルチステージ型継続的インテグレーションのすすめ
 
WorldAffairs 2005: Meeting the Challenges of the Middle East
WorldAffairs 2005: Meeting the Challenges of the Middle EastWorldAffairs 2005: Meeting the Challenges of the Middle East
WorldAffairs 2005: Meeting the Challenges of the Middle East
 
Library tech
Library techLibrary tech
Library tech
 
WorldAffairs 2012: Navigating in a Shifting Global Landscape
WorldAffairs 2012: Navigating in a Shifting Global LandscapeWorldAffairs 2012: Navigating in a Shifting Global Landscape
WorldAffairs 2012: Navigating in a Shifting Global Landscape
 
E-Book Marketing Eleitoral
E-Book Marketing EleitoralE-Book Marketing Eleitoral
E-Book Marketing Eleitoral
 
мотивация власти презентация григорьева
мотивация власти презентация григорьевамотивация власти презентация григорьева
мотивация власти презентация григорьева
 
новый покупатель Xxi века
новый покупатель Xxi векановый покупатель Xxi века
новый покупатель Xxi века
 
Chiude acerra , più navi per i rifiuti
Chiude acerra , più navi per i rifiutiChiude acerra , più navi per i rifiuti
Chiude acerra , più navi per i rifiuti
 

Similar to Week 12 code

Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
meerobertsonheyde608
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
Mouli Chandira
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
Taha Shakeel
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
ccherubino
 

Similar to Week 12 code (20)

Simpan data- ke- database
Simpan data- ke- databaseSimpan data- ke- database
Simpan data- ke- database
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 
TypeScriptで書くAngularJS @ GDG神戸2014.8.23
TypeScriptで書くAngularJS @ GDG神戸2014.8.23TypeScriptで書くAngularJS @ GDG神戸2014.8.23
TypeScriptで書くAngularJS @ GDG神戸2014.8.23
 
Michael Colon Portfolio
Michael Colon PortfolioMichael Colon Portfolio
Michael Colon Portfolio
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
SOLID Java Code
SOLID Java CodeSOLID Java Code
SOLID Java Code
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
dfhdf
dfhdfdfhdf
dfhdf
 
Android Testing
Android TestingAndroid Testing
Android Testing
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Using database in android
Using database in androidUsing database in android
Using database in android
 
Enterprise workflow with Apps Script
Enterprise workflow with Apps ScriptEnterprise workflow with Apps Script
Enterprise workflow with Apps Script
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 

Recently uploaded

Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Recently uploaded (20)

Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 

Week 12 code

  • 1. <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form action="index.jsp" method="post"> First Name: <input type="text" name="firstName"><br> Last Name: <input type="text" name="lastName"><br> Email Address: <input type="text" name="emailAddress"><br> <input type="submit" Value="Submit"> </form> </body> </html>
  • 2. <%@pagecontentType="text/html" pageEncoding="UTF-8"%> <%@page import="java.sql.*, business.User, javax.servlet.*, java.io.*, javax.servlet.http.*, java.sql.*, java.util.*, util.SQLDBUtil" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>mySQL</h1> <% User user; try { String dbUrl = "jdbc:mysql://localhost:3306/murach"; String username = "root"; String password = "sesame"; String query = "SELECT * FROM murach.user"; String userName = ""; SQLDBUtilutil = new SQLDBUtil(); ArrayList<User> users = new ArrayList<User>(); //insert a new record util.insertUser(request.getParameter("firstName"),request.getParameter("lastName"),request.getParamet er("emailAddress")); Connection conn = DriverManager.getConnection(dbUrl, username, password); PreparedStatementps = conn.prepareStatement(query); Statement statement = conn.createStatement(); ResultSetrs = statement.executeQuery(query); while(rs.next()) { user = new User(rs.getString(2),rs.getString(3),rs.getString(4)); users.add(user); //userName = user.getFirstName(); } rs.close(); Iterator it = users.iterator(); User tempUser; %> <table cellpadding="5" cellspacing="5" border =" 1"> <% while(it.hasNext()) {
  • 3. tempUser = (User) it.next(); %> <tr> <td>First Name:</td> <td><%= tempUser.getFirstName() %></td> <td> Last Name: </td> <td><%= tempUser.getLastName() %></td> <td> Email Address: </td> <td><%= tempUser.getEmailAddress() %></td> <br> </tr> <% } %> </table> <% } catch (SQLException e) { for (Throwable t : e) t.printStackTrace(); } finally { } %> </body> </html>
  • 4. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package business; /** * * @author tpersson */ public class User { String firstName, lastName, emailAddress; public User () { } public User (String first, String last, String email) { firstName = first; lastName = last; emailAddress = email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmailAddress() { return emailAddress; } }
  • 5. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package util; importjava.sql.*; import business.User; import javax.servlet.*; import java.io.*; import javax.servlet.http.*; import java.sql.*; import java.util.*; /** * * @author tpersson */ public class SQLDBUtil{ String dbUrl = "jdbc:mysql://localhost:3306/murach"; String username = "root"; String password = "sesame"; String query = ""; //connection objects Connection conn; PreparedStatementps; Statement statement; publicSQLDBUtil() { } public void insertUser(String first, String last, String email) { //query = "INSERT INTO murach.user('',first, last, email)"; query = "INSERT into murach.user (FirstName,LastName,EmailAddress) values ('" + first + "','" + last + "','" + email + "')"; runQuery(query); } public void updateUser(String first, String last, String email) { if(doesExist(email)) { query = "UPDATE murach.user SET FirstName ='"+ first +"',LastName='"+last+"',EmailAddress='"+email2 +"' WHERE EmailAddress='" + email +"'"; runQuery(query); } else { //out.printLine("No record with that email address"); } }
  • 6. private void connectDb() { try { conn = DriverManager.getConnection(dbUrl, username, password); } catch (SQLException e) { } finally { } } private void runQuery(String q) { try { connectDb(); PreparedStatementps = conn.prepareStatement(query); Statement statement = conn.createStatement(); ps.executeUpdate(); conn.close(); } catch (SQLException e) { } finally { } } private booleandoesExist(String email) { Boolean exists = false; ResultSetrsCheck; connectDb(); query="SELECT * FROM murach.User WHERE EmailAddress='" + email + "'"; try { ps = conn.prepareStatement(query); statement = conn.createStatement(); rsCheck = statement.executeQuery(query); rsCheck.last(); if(rsCheck.getRow()>0) { exists = true; } } catch(SQLException e) { } finally { return exists; }
  • 7. } }