mysql(二)

程序連接Mysql

1.Java代碼示例
  • JDBC客戶端應用 -> java.sql.或javax.sql. -> 驅動程序 -> SQLserver/Oracle/MySQL
    結構:

  • DriverManager -> Driver(是驅動程序對象的接口,指向具體數據庫驅動程序對象)=DriverManager.getDriver(String URL) -> Connectinon(是連接對象接口,指向具體數據庫連接對象)=DriverManager.getConnection(String URL) -> Statement(執行靜態SQL語句接口)=Connection.CreateStatement() -> ResultSet(是指向結果集對象的接口)=Statement.excuteXXX()

import com.mysql.jdbc.Connection;



import java.sql.*;

import javax.swing.text.DefaultEditorKit.InsertBreakAction;

public class Conntect {

    public static Connection getConnection()throws SQLException,java.lang.ClassNotFoundException
    {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/testdao";
        String username= "root";
        String password = "root";
        Connection conn = (Connection) DriverManager.getConnection(url,username,password);
        return conn;
    }
    public static void main(String args[]) throws SQLException
    {

        Connection con = null;
        try
        {
            con = getConnection();
            Statement sql_statement = con.createStatement();
            sql_statement.executeUpdate("drop table if exists test;");
            sql_statement.executeUpdate("create table test(user varchar(20) not null ,"
                    + "leixing varchar(20) "
                    + "not null,score varchar(20) not null,"
                    + "primary key(user,leixing));");
            String[] a= new String[]{"li","age", "18","li", "dep", "2","li","sex","male","sun","age","44","sun","sex","female","sun","dep","3","wang","age","20","wang","dep","3","wang","sex","male"};
//          System.out.println(a.length);
            for(int i=0;i<a.length;i+=3)
            {

//              System.out.println(i);
                String sql = "insert into test values('"+a[i]+"','"+a[i+1]+"','"+a[i+2]+"');";
//              System.out.println(sql);
                sql_statement.executeUpdate(sql);
            }


            sql_statement.execute("insert into test values('zxc','age','22');");

            sql_statement.execute("update test set score='77' where user='zxc' and leixing='age';");


            int num = sql_statement.executeUpdate("delete from test where user='zxc';");
            System.out.println(num);


            String query = "select * from test;";
            ResultSet result = sql_statement.executeQuery(query);
            while (result.next())
            {
                String cname = result.getString("user");
                String cource = result.getString("leixing");
                String score = result.getString("score");
                System.out.println("姓名:"+cname+" 類型:"+cource+" 分數:"+score);
            }
            result.close();
            sql_statement.close();

            String sql1 = "insert into test value(?,?,?)";
            PreparedStatement prsa = con.prepareStatement(sql1);
            prsa.setString(1, "zxc");
            prsa.setString(2, "age");
            prsa.setString(3, "55");
             num= prsa.executeUpdate();
            System.out.println(num+"rows has insert");


            String sql = "update test set score=? where user=? and leixing=?";
            prsa = con.prepareStatement(sql);

            prsa.setString(1, "23");

            prsa.setString(2, "zxc");
            prsa.setString(3, "age");

            num= prsa.executeUpdate();
            System.out.println(num+"rows has changed");

            prsa.close();

            query = "select * from test;";
            PreparedStatement ps = (PreparedStatement) con.prepareStatement(query,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
            ps.setFetchSize(Integer.MIN_VALUE);
            result =  ps.executeQuery();
            while (result.next())
            {
                String cname = result.getString("user");
                String cource = result.getString("leixing");
                String score = result.getString("score");
                System.out.println("姓名:"+cname+" 類型:"+cource+" 分數:"+score);
            }

            result.close();
            ps.close();
            con.close();
        }
        catch(java.lang.ClassNotFoundException e){
            System.err.print("ClassNotFoundException");
        }
        catch(SQLException e)
        {
            System.err.print("SQL exception"+e.getMessage());
        }

    }
}

Statement與PreparedStatement的區別

  • connection, Statement與ResultSet關閉的意義
  • jdbc連接參數的使用
  • ResultSet遊標的使用(setFetchSize)
  • Statement與PreparedStatement的區別

PreparedStatement在數據庫端預編譯,效率高,可以防止SQL注入。

  • 對數據庫執行一次性存取的時候,用Statement對象進行處理。
    線上業務推薦使用PreparedStatement.
    connection, Statement與ResultSet關閉的意義
MySQL數據庫端爲connection與ResultSet維護內存狀態,一直不關閉會佔用服務端資源。
  • MySQL最大連接數受max_connections限制,不能無限創建連接,所以用完要及時關閉。
    JDBC connection關閉後ResultSet, Statement會自動關閉。但是如果使用連接池將不會關閉,因此推薦主動關閉。

ResultSet遊標的使用

  • 默認的ResultSet對象不可更新,僅有一個向前移動的指針。因此,只能迭代它一次,並且只能按從第一行到最後一行的順序進行。可以生成可滾動和/或可更新的ResultSet對象。
    setFetchSize()是設置ResultSet每次向數據庫取的行數,防止數據返回量過大將內存爆掉。
#####2.Python代碼示例
* Python操作mysql數據庫需要MySQL-python驅動
如果電腦有pip或者easyinstall可以直接安裝

pip install MySQL-python
easy_install MySQL-python


#coding:utf-8
import MySQLdb
conn = MySQLdb.connect(host=”localhost”,port=3308,user=”root”,passwd=”root”)
#建立與數據庫的連接
curs= conn.cursor()
#獲取遊標
conn.select_db(‘testdao’)
#選擇數據庫testdao

curs.execute(“update test set score=’56’ where user=’zxc’ and leixing=’age’”)
print curs.fetchone()
#獲取一條記錄,以一個元組返回
values = [(‘zxc’,’sex’,’male’),(‘zxc’,’dep’,’4’)]
curs.executemany(“insert into test values(%s,%s,%s)” ,values)
conn.commit()
#執行插入多條數據要用exectemany,並提交
curs.execute(“select * from test”)
result = curs.fetchall()
for item in result:
print “姓名:”+item[0]+”類型:”+item[1]+”分數”+item[2]
#獲取所有的記錄,以一個元組返回

curs.close()
conn.close()
#關閉連接

  • cursor用來執行命令的方法:

  • callproc(self,procname,args)
    用來執行存儲過程,接收的參數爲存儲過程名和參數列表,返回值爲受影響的行數

  • execute(self, query, args)
    執行單條sql語句,接收的參數爲sql語句本身和使用的參數列表,返回值爲受影響的行數

  • executemany(self, query, args)
    執行單挑sql語句,但是重複執行參數列表裏的參數,返回值爲受影響的行數

  • nextset(self)
    移動到下一個結果集

  • cursor用來接收返回值的方法:

  • fetchall(self)
    接收全部的返回結果行

  • fetchmany(self, size=None)
    接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據

  • fetchone(self)
    返回一條結果行

  • scroll(self, value, mode=’relative’)
    移動指針到某一行,如果mode=’relative’,則表示從當前所在行移動value條,如果 mode=’absolute’,則表示從結果集的第一行移動value條。

( 於2016年6月21日,http://blog.csdn.net/bzd_111

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章