1.Python创建数据库

import MySQLdb
try:
conn = MySQLdb.connect(
host="127.0.0.1",
port=3306,
user="root",
passwd="",
# db="juntest",#也可以在这一步显示数据库名
charset="utf8")
cur = conn.cursor()
cur.execute('CREATE DATABASE IF NOT EXISTS juntestDBnew DEFAULT CHARSET utf8 COLLATE utf8_general_ci;') #没有这个表,就创建
conn.close()
print u"创建数据库juntestDBnew成功! "
except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

创建成功,查看

2.创建数据表

#coding=utf-8
import MySQLdb
try:
conn = MySQLdb.connect(
host="127.0.0.1",
port=3306,
user="root",
passwd="",
# db="juntest",另外写一种建表的方法
charset="utf8")
conn.select_db('juntestDBnew')#选择一个数据库
cur = conn.cursor()
cur.execute("drop table if exists emp_info2;")
cur.execute("drop table if exists salary2;")
cur.execute('''create table emp_info2(
id int not null auto_increment,
name varchar(30) not null,
sex char(4) default null,
dept varchar(10),
mobile varchar(11) not null unique,
birthday date default "0000-00-00",
primary key(id)
)engine=innodb character set utf8 comment 'employer info';
''')
cur.execute('''create table salary2(
id int not null auto_increment,
emp_id int not null,
salary int not null,
primary key(id)
)engine=innodb character set utf8 comment 'employer salary info';
''')
cur.close()
conn.close()
print u"创建数据表成功! " except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

查看是否成功

3.进行数据的插入

#coding=utf-8
import MySQLdb
import random try:
conn = MySQLdb.connect(
host="127.0.0.1",
port=3306,
user="root",
passwd="",
db="juntestDBnew",#另外写一种建表的方法
charset="utf8"
)
cur=conn.cursor()
num=random.randint(10,300)
sql="insert into emp_info2 values(%s,%s,%s,%s,%s,%s)"#这种写法自增字段和隐藏字段都要写出来
#cur.execute(sql, (4, 'jun1', 'm', 'jun', '12345', '2017-4-30'));
for i in range(1,10):
cur.execute('delete from emp_info2 where id='+str(i));
#第一种插入
cur.execute(sql, (i, 'jun'+str(i), 'm', 'jun', ''+str(random.randint(1,1000)), '2017-4-'+str(random.randint(1,30))));
print u"插入第(%s)条数据成功"%i
cur.close()
conn.commit()
conn.close() except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])

python连接数据库并插入数据的更多相关文章

  1. python 定义一个插入数据(可以插入到每个表中)通用的方法

    前提置要:想要写一个方法,这个方法是插入数据到数据表的方法,只需要提供表名称,字段名称,还有插入的值,只要调用这个方法就可以自动帮助你插入数据 以下是不断实践优化出来 原本的插入数据库中的代码应该是这 ...

  2. go : 连接数据库并插入数据

      package main import ( "database/sql" "fmt" "log" "net/http" ...

  3. python 向mysql插入数据

    生成随机内容用到的方法: substr是一个字符串函数,从第二个参数1,开始取字符,取到3 + floor(rand() * 75)结束 floor函数代表的是去尾法取整数. rand()函数代表的是 ...

  4. Java使用JDBC连接数据库逐条插入数据、批量插入数据、以及通过SQL语句批量导入数据的效率对比

    测试用的示例java代码: package com.zifeiy.test.normal; import java.io.File; import java.io.FileOutputStream; ...

  5. python向数据库插入数据时出现乱码解决方案

    中文字符串前面加u 如: title =u"你好" contents = "m" ids="13" cur.execute("IN ...

  6. 集群Redis使用 Python pipline大批量插入数据

    class myRedis(object):     def __init__(self,redis_type=None,**args):         if redis_type == " ...

  7. 单节点Redis使用 Python pipline大批量插入数据

    方法一: import redis import time filename = 'redis_resulit.txt' def openPool():     pool = redis.Connec ...

  8. Python中MySQL插入数据

    sql = 'INSERT INTO course(class_name, credit, properties, teacher_name, college_given, classroom) ' ...

  9. 解决Python往MySQL插入中文时报错的问题

    今天遇到一个问题,用Python往MySQL插入数据时,若数据中包含中文会报类似下面的错误: ERROR 1366: Incorrect string value: '\xE4\xB8\xAD\xE5 ...

随机推荐

  1. [转]使用ASP.NET Web API 2创建OData v4 终结点

    本文转自:http://www.cnblogs.com/farb/p/ODataAspNetWebAPI.html 开放数据协议(Open Data Protocol[简称OData])是用于Web的 ...

  2. ubuntu16.04 安装 nginx 服务器

    在线安装 apt-get install nginx 说明 启动程序文件在/usr/sbin/nginx 日志放在了/var/log/nginx中,分别是access.log和error.log 并已 ...

  3. 二:Bootstrap-css组件

    Glyphicons 图标: span.glyphicon glyphicon-align-center 下拉菜单: div.dropdown/div.btn-group button[data-to ...

  4. 六、curator recipes之屏障barrier

    简介 curator针对分布式场景实现了分布式屏障:barrier.我们在分布式系统中可以使用barrier去阻塞进程,知道某个条件被触发.其实跟Java多线程的barrier是一样的. 例如:当两个 ...

  5. layui使用 ——父,子页面传值

    页面传值是非常常用的,layui自带弹窗功能,但是内置使用的是location.href 暂时没找到方法条件请求头,所以在后台需要放开拦截器, layer.open({ type : 2, title ...

  6. csu 1356 Catch bfs(vector)

    1356: Catch Time Limit: 2 Sec  Memory Limit: 128 MBSubmit: 96  Solved: 40[Submit][Status][Web Board] ...

  7. MySQL数据导出为Excel, json,sql等格式

    MySQL数据经常要导出为Excel, json,sql等格式,通过步骤都很多,麻烦,现在通过Treesoft可以方便的导出你要的数据格式. 1.在线执行SQL,在数据列表中有相应按钮,方便的将数据导 ...

  8. PAT 1029. Median

    尼玛,数组偶数个数的时候取中位数是取中间两者中的前者,还tmd一直再算平均,卧槽 #include <iostream> #include <cstdio> #include ...

  9. ES6学习笔记(三)-正则扩展

    PS: 前段时间转入有道云笔记,体验非常友好,所以笔记一般记录于云笔记中,每隔一段时间,会整理一下, 发在博客上与大家一起分享,交流和学习. 以下:

  10. RequireJS 是一个JavaScript模块加载器

    RequireJS 是一个JavaScript模块加载器.它非常适合在浏览器中使用, 它非常适合在浏览器中使用,但它也可以用在其他脚本环境, 就像 Rhino and Node. 使用RequireJ ...