mysql(二)

3 篇文章 0 订阅
1 篇文章 0 订阅

程序连接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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值