Java Novice Note 34 connection database

Source: Internet
Author: User
Tags odbc readline

1.JdbcUtil

Package Com.yfs.javase.jdbc;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.ResultSet; Import Java.sql.sqlexception;import Java.sql.statement;public class Jdbcutil {private static final String Driver = "SUN.J Dbc.odbc.JdbcOdbcDriver ";p rivate static final String url =" Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D bq= School.mdb ";//Get connection method public static Connection getconnection () {Connection conn = null;//Connect database try {class.forname (driver) ; conn = drivermanager.getconnection (URL);} catch (ClassNotFoundException e) {System.out.println ("Driver class not found ..."); catch (SQLException e) {System.out.println ("Connection database failed ..."); Return conn;} Release connection public static void release (ResultSet RS, Statement St, Connection conn) {try {if (rs! = null) {Rs.close ();}} catch (SQLException e) {E.printstacktrace ();} Finally {try {if (st! = null) {St.close ()}} catch (SQLException e) {e.printstacktrace ();} finally {try {if (conn! = null) {Conn.close ();}} catch (SQLException e) {e.printstacktrace ();}}}}

2. Connection Information: Jdbc.properties file

# #oracle \u9a71\u52a8jdbc.driver = Oracle.jdbc.OracleDriverjdbc.url = Jdbc:oracle:thin: @YEMA203 -13:1521:yfs_ Dbjdbc.username = Scottjdbc.password = tiger# #SQL Server 2005#jdbc.driver = Com.microsoft.sqlserver.jdbc.sqlserverdriver#jdbc.url = jdbc:sqlserver://localhost:1434;databasename=yfs_db# Jdbc.username = Sa#jdbc.password = # #MySQL #jdbc.driver = Com.mysql.jdbc.driver#jdbc.url = jdbc:mysql://localhost:3306/ Test#jdbc.username = Root#jdbc.password = root# #Access #jdbc.driver = Sun.jdbc.odbc.jdbcodbcdriver#jdbc.url = Jdbc:odbc :d river={microsoft Access Driver (*.mdb)};D Bq=yfs_db.mdb    

3.JDBCDEMO1 test SQL Execution (increase, check, change, delete)

Package Com.yfs.javase.jdbc;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.SQLException; Import Java.sql.statement;public class JdbcDemo1 {public static void main (string[] args) throws Exception {//createtable ( );//insertdata ();//updata ();//deletedata (); Create ();} public static void Create () throws Exception {Connection conn = jdbcutil.getconnection (); Statement st = Conn.createstatement ();//SQL statement executed by string sql = "CREATE TABLE stu (ID int primary key, name Char (), score I NT) ";//execute St.execute (SQL);//close connection jdbcutil.release (null, ST, conn); SYSTEM.OUT.PRINTLN ("Table created successfully ..."); public static void DeleteData () throws Exception {Connection conn = jdbcutil.getconnection (); Statement st = Conn.createstatement ();//Execute SQL statement String sql = "Delete from Stu where id=102";//execute St.execute (SQL);//Close Connection J Dbcutil.release (NULL, ST, conn); System.out.println ("Delete data successfully ...");} public static void Updata () throws Exception {Connection conn = jdbcutil.getconnection (); Statement st = Conn.createstatemeNT ();//Execute SQL statement String sql = "Update stu set score=80 where id=102";//execute St.execute (SQL);//close connection st.close (); Conn.close (); SYSTEM.OUT.PRINTLN ("Update data successfully ...");} public static void InsertData () throws Exception {//Load driver Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");//urlstring URL = "Jdbc:odbc:driver={microsoft Access Driver (*.mdb)};D Bq=e:/school.mdb";//Get connection Connection conn = Drivermanager.getconnection (URL);//URL database address//Execution Object Statement st = Conn.createstatement ();//SQL statement executed//string sql = " Insert into Stu (Id,name,score) VALUES (101, ' Mustang ', 98) "; String sql = "INSERT into Stu (Id,name,score) VALUES (102, ' Transformers 4 ', 65)";//execute St.execute (SQL);//close connection st.close (); conn.close (); System.out.println ("Insert data successfully ...");} public static void CreateTable () throws Exception {//Load driver Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");//URLString url = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D Bq=e:/school.mdb";//Get connection Connection conn = Drivermanager.getconnection (URL);//URL database address//Execution Object Statement st = Conn.createstatement();//Execute SQL statement String sql = "CREATE TABLE stu (ID int primary key, name Char (), score int)";//execute St.execute (SQL);//Close Connection St . Close (); Conn.close (); SYSTEM.OUT.PRINTLN ("Database operation succeeded ...");}}

 4.server3

Package Com.yfs.javase;import Java.io.bufferedoutputstream;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.OutputStream; Import Java.io.outputstreamwriter;import java.io.printwriter;import java.net.serversocket;import java.net.Socket; Import Java.util.scanner;public class Server3 {/** * Boot service listener port */public static void Main (string[] args) throws Exception { ServerSocket Server = new ServerSocket (3000);//Start System.out.println ("Server boot, listen 3000 ports ..."); final socket socket = Server.accept ();//monitor If there are other hosts connected to string other = Socket.getinetaddress (). gethostaddress ();  System.out.println (Other + "request connection ...");//Receive information start multithreading new Thread (new Runnable () {@Overridepublic void run () {InputStream in = Null BufferedReader read = Null;while (true) {try {in = Socket.getinputstream (); read = new BufferedReader (New InputStreamReader (in)); String msg = Read.readline (), if (msg! = null) {SYSTEM.OUT.PRINTLN ("client says:" + msg);}} catch (IOException E) {E.printstacktrace ();}}}). Start ();//send information to get output stream outputstream out = Socket.getoutputstream (); Bufferedoutputstream buf = new Bufferedoutputstream (out); PrintWriter pw = new PrintWriter (new OutputStreamWriter (BUF), true);p w.println ("This is information sent by the server ...."); Scanner scan = new Scanner (system.in); String msg = Scan.next (), while (!msg.equals ("Bye")) {pw.println (msg); msg = Scan.next ();} Pw.close (); Buf.close (); Out.close (); SYSTEM.OUT.PRINTLN ("Send Message Complete");}}

 4.client3

Package Com.yfs.javase;import Java.io.bufferedinputstream;import Java.io.bufferedreader;import java.io.IOException ; Import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.outputstreamwriter;import Java.io.printwriter;import Java.net.socket;import Java.util.Scanner;public class Client3 {/** * @param args */public static void main (string[] args) throws Exception {final socket socket = new Socket ("19 2.168.1.30 ", 3000);//Receive Message New Thread (new Runnable () {@Overridepublic void run () {inputstream in = null; BufferedReader Read = null;try {in = Socket.getinputstream (); read = new BufferedReader (new InputStreamReader (in)); String msg = Read.readline (); while (msg! = null) {SYSTEM.OUT.PRINTLN ("server says:" + msg); msg = Read.readline ();}} catch (IOException e) {e.printstacktrace ();}}}). Start ();//send information outputstream out = Socket.getoutputstream (); PrintWriter pw = new PrintWriter (new OutputStreamWriter (out), true); Scanner scan = new Scanner (system.in); String msg = sCan.next (); while (!msg.equals ("Bye")) {pw.println (msg); msg = Scan.next ();} Out.close ();p w.close ();}}

Java Novice Note 34 connection database

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.