GVKun编程网logo

mysql之UPDATE,SELECT,INSERT语法

14

此处将为大家介绍关于mysql之UPDATE,SELECT,INSERT语法的详细内容,此外,我们还将为您介绍关于6-Python操作MySQL-增(insert)-删(delete)-改(updat

此处将为大家介绍关于mysql之UPDATE,SELECT,INSERT语法的详细内容,此外,我们还将为您介绍关于6-Python操作MySQL-增(insert)-删(delete)-改(update)-查(select)、c# – TSQL:带INSERT INTO SELECT FROM的UPDATE、C++类库:OTL连接MySQLODBC数据库(insert,update,select)_MySQL、MyBatis XML 映射器 select、insert update 和 delete、参数的有用信息。

本文目录一览:

mysql之UPDATE,SELECT,INSERT语法

mysql之UPDATE,SELECT,INSERT语法

<h3>一 :UPDATE语法

teral">   是一个修改表中行的DML语句。

table_reference , table_reference2
value:  ()
    {expr | DEFAULT} #值可以是表达式或默认值   例如   col1 

assignment:
col_name = value # col_name 列名

assignment_list:
assignment [,assignment] ...

二:SELECT语法(常用语法,与官方有点差别,主要是删除了一些可选参数)

  用于检索从一个或多个表中选择的行

,... row_count 分页

注意:除select_expr其他都是可选参数

语法解析:

1.select_expr 选择表达式 (多个表达式需要用‘,’分割)

  例如: table.列名  (映射)

  例如:  full_name  (聚合函数和别名  连接多列的字段),和直接调用其他集合函数

(  t3.`CATEGORY` = 2   `T`.`ADDRES`  NULL ) AS `ADDRES`  (选择表达式,可选着显示内容  例 当''t3.CATEGORY = 2 " 为真时显示THEN后值  为false时显示ELSE的值)

2.where_condition 条件表达式

  例如 :id = 2 (当id等于2时为真时显示该数据)

  例如 :NOT EXISTS ( select id form classes where id = 5)   (即一个子查询并判断查询的结果是否显示数据) 注意子查询可用父查询的表数据作为条件

3.  GROUP BY 分组 根据列进行分组(列的类型可以是字符串。。。。)

  例如 :对单列分组》group by id  (默认是ASC升序,)指定分组方式 group by id ASC

  例如: 对多列进行分组    GROUP BY c.id ASC,t.`tid` DESC;  (并按不同方式)

4.  HAVING 包含

5. ORDER BY  排序可参考group by 都有按不同方式排序

6. LIMIT  分页

三:INSERT语法

norE     VALUE} (value_list) 语法2 () norE tbl_name ...)] ...
 score+1
value_list:
    value   ...

解析语法:

 语法1    除table(表名)和value(值) 为必选其他都是可选

     例如 :  默认值)

查询出来的值 理解为语法1中的value (可用于快熟复制一天记录)

classes(id)   classes c c.id=4; # 插入一条空数据,

1:[ ] : 顾名思义 ignore是忽略的意识,结合官方文档和自己的理解如下

        如果用insert 插入数据,并且用‘ignore’关键字修饰了insert,则当插入数据发生错误时MysqL服务器会忽略该错误并转换为warning信息,并继续执行下条插入信息。

  例如 :  执行插入   norE  teacher(tid,class_id,NAME) (14,1,'teacher12'),(15,'teacher11');  (teacher表信息 tid 为主键  且tid=14已经存在,tid=15不存在)

     执行结果:

     分析:当执行插入tid=14时发生了错误,服务器忽略了该错误并转化为警告信息,并继续执行了tid=15的数据

 可利用该特性:,即当该条数据(id)已经存在发出警告,否则就执行插入

2:[  ] :当key发生DUPLICATE (重复错误)时执行 update语句 》

  例如: teacher(tid,NAME) (14,'teacher12') class_id=1,NAME='teacher1233333';

    即当tid=14已经存在就执行更新语句,否则就执行insert语句;

6-Python操作MySQL-增(insert)-删(delete)-改(update)-查(select)

6-Python操作MySQL-增(insert)-删(delete)-改(update)-查(select)

增删改

from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host=''localhost'',port=3306,database=''jing_dong'',user=''root'',password=''mysql'',charset=''utf8'')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行insert语句,并返回受影响的行数:添加一条数据
    # 增加
    count = cs1.execute(''insert into goods_cates(name) values("硬盘")'')
    #打印受影响的行数
    print(count)

    count = cs1.execute(''insert into goods_cates(name) values("光盘")'')
    print(count)

    # # 更新
    # count = cs1.execute(''update goods_cates set name="机械硬盘" where name="硬盘"'')
    # # 删除
    # count = cs1.execute(''delete from goods_cates where id=6'')

    # 提交之前的操作,如果之前已经之执行过多次的execute,那么就都进行提交
    conn.commit()

    # 关闭Cursor对象
    cs1.close()
    # 关闭Connection对象
    conn.close()

if __name__ == ''__main__'':
    main()

# 查询一行数据
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host=''localhost'',port=3306,user=''root'',password=''mysql'',database=''jing_dong'',charset=''utf8'')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行select语句,并返回受影响的行数:查询一条数据
    count = cs1.execute(''select id,name from goods where id>=4'')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    for i in range(count):
        # 获取查询的结果
        result = cs1.fetchone()
        # 打印查询的结果
        print(result)
        # 获取查询的结果

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == ''__main__'':
    main()

# 查询多行数据
from pymysql import *

def main():
    # 创建Connection连接
    conn = connect(host=''localhost'',port=3306,user=''root'',password=''mysql'',database=''jing_dong'',charset=''utf8'')
    # 获得Cursor对象
    cs1 = conn.cursor()
    # 执行select语句,并返回受影响的行数:查询一条数据
    count = cs1.execute(''select id,name from goods where id>=4'')
    # 打印受影响的行数
    print("查询到%d条数据:" % count)

    # for i in range(count):
    #     # 获取查询的结果
    #     result = cs1.fetchone()
    #     # 打印查询的结果
    #     print(result)
    #     # 获取查询的结果

    result = cs1.fetchall()
    print(result)

    # 关闭Cursor对象
    cs1.close()
    conn.close()

if __name__ == ''__main__'':
    main()

 

c# – TSQL:带INSERT INTO SELECT FROM的UPDATE

c# – TSQL:带INSERT INTO SELECT FROM的UPDATE

所以我有一个旧的数据库,我正在迁移到一个新的数据库.新的具有略微不同但大多数兼容的模式.此外,我想从零重新编号所有表.

目前,我一直在使用我写的工具手动检索旧记录,将其插入新数据库,并更新旧数据库中的v2 ID字段,以在新数据库中显示其对应的ID位置.

例如,我从MV5.Posts中选择并插入MV6.Posts.插入后,我检索MV6.Posts中新行的ID,并在旧的MV5.Posts.MV6ID字段中进行更新.

有没有办法通过INSERT INTO SELECT FROM做这个UPDATE,所以我不必手动处理每个记录?我正在使用sql Server 2005,开发版.

解决方法

迁移的关键是做几件事情:
首先,不要做任何没有当前的备份.
第二,如果密钥正在更改,您需要至少临时存储新结构中的旧的和新的(永久地,如果密钥字段暴露给用户,因为它们可能被搜索以获取旧的记录).

接下来,您需要彻底了解与子表的关系.如果更改关键字段,所有相关表格也必须更改.这是存储旧密钥和新密钥的地方派上用场的地方.如果您忘记更改任何内容,数据将不再正确,无效.所以这是一个关键的一步.

挑选一些特别复杂数据的测试用例,确保为每个相关表格包含一个或多个测试用例.将现有值存储在工作表中.

要启动迁移,请使用旧表中的select插入到新表中.根据记录的数量,您可能需要循环访问批次(不能一次记录),以提高性能.如果新密钥是一个身份,您只需将旧密钥的值放在其字段中,并让数据库创建新密钥.

然后对相关的表进行相同的操作.然后使用表中的旧键值更新外键字段:

Update t2
set fkfield = newkey
from table2 t2
join table1 t1 on t1.oldkey = t2.fkfield

通过运行测试用例并将数据与迁移前存储的数据进行比较来测试迁移.彻底测试迁移数据至关重要,或者您无法确定数据与旧结构是一致的.移民是一个非常复杂的行动;它花费你的时间,并且非常有条不紊地做到这一点.

C++类库:OTL连接MySQLODBC数据库(insert,update,select)_MySQL

C++类库:OTL连接MySQLODBC数据库(insert,update,select)_MySQL

一. 简介

OTL是一个纯C++的通用数据库连接模板库,可以支持各种当下流行的数据库,如Oracle,Sybase, MySQL, PostgreSQL, EnterpriseDB, SQLite, MS ACCESS, Firebird等等.它是一个跨平台类库,在MS Windows, Linux/Unix/Mac OS X 都可以使用。

OTL使用简单, 只要头文件中包含有: #include "otlv4.h" 就可,实际上整个OTL就一个.H的文件,使用起来极为的方便。

我的下载空间:

代码:http://download.csdn.net/detail/u013354805/9057229

文档:http://download.csdn.net/detail/u013354805/9057243

立即学习“C++免费学习笔记(深入)”;

案例:http://download.csdn.net/detail/u013354805/9057273

官方下载地址:http://otl.sourceforge.net/

二. 使用方法:

1. 首先指定要连接的数据库类型,OTL用宏定义来指定要连接的数据库类型。OTL会根据这个宏定义来初始化数据库连接的环境。

相关的宏定义列表: http://otl.sourceforge.net/otl3_compile.htm

如: #define OTL_ODBC_MYSQL表示连接ODBC MySQL数据库。

2、案例:

1) 指定连接的数据库类型:

#define OTL_ODBC_MYSQL // 指定连接的数据库类型
登录后复制

2) 导入OTL 4 头文件

#include <otlv4.h> // include the OTL 4 header file
登录后复制

3) 定义数据库实例:

otl_connect db; // 定义数据库实例
登录后复制

4) 初始化ODBC环境:

otl_connect::otl_initialize();
登录后复制

5) 连接ODBC:

db.rlogon("UID=scott;PWD=tiger;DSN=mysql"); // connect to ODBC
登录后复制

6). 删除表格:

otl_cursor::direct_exec
   (
    db,
    "drop table test_tab",
    otl_exception::disabled // disable OTL exceptions
   ); // drop table
登录后复制

7). 创建表格:

otl_cursor::direct_exec
   (
    db,
    "create table test_tab(f1 int, f2 varchar(30))"
    );  // create table
登录后复制

8). Insert 语句:

// insert rows into table
 void insert()
{ 
	 otl_stream o(1, // buffer size should be == 1 always on INSERT
	              "insert into test_tab values(:f1<int>,:f2<char[31]>)", 
	                 // SQL statement
	              db // connect object
	             );
	 char tmp[32];

	 for(int i=1;i<=100;++i)
	 {
	  sprintf(tmp,"Name%d",i);
	  o<<i<<tmp;
	 }
}
登录后复制


9). Update 语句:

// update row data into table
void update(const int af1)
{ 
	 otl_stream o(1, // buffer size should be == 1 always on UPDATE
				  "UPDATE test_tab "
				  "   SET f2=:f2<char[31]> "
				  " WHERE f1=:f1<int>", 
					 // UPDATE statement
				  db // connect object
				 );
	 o<<"Name changed"<<af1;
	 o<<otl_null()<<af1+1; // set f2 to NULL
}
登录后复制

10). Select语句:

// MyODBC does not allow any input bind variables in the WHERE clause
// in a SELECT statement.
// Therefore, the SELECT statement has to be generated literally.
void select(const int af1)
{ 
	 char stmbuf[1024];
	 sprintf(stmbuf,
	         "select * from test_tab where f1>=%d and f1<=%d*2",
	         af1,
	         af1
	        );
	 otl_stream i(50, // buffer size may be > 1
	              stmbuf, // SELECT statement
	              db // connect object
	             ); 
	   // create select stream
	 
	 int f1;
	 char f2[31];

	 while(!i.eof())
	 { // while not end-of-data
		  i>>f1;
		  cout<<"f1="<<f1<<", f2=";
		  i>>f2;
		  if(i.is_null())
		   cout<<"NULL";
		  else
		   cout<<f2;
		  cout<<endl;
	 }

}
登录后复制

11). 断开ODBC:

db.logoff(); // disconnect from ODBC
登录后复制

12). 案例:

int main()
{
	 otl_connect::otl_initialize(); // initialize ODBC environment
	 try
	 {

		  db.rlogon("UID=scott;PWD=tiger;DSN=mysql"); // connect to ODBC
		  //  db.rlogon("scott/tiger@mysql"); // connect to ODBC, alternative format
		                                     // of connect string 

		  otl_cursor::direct_exec
		   (
		    db,
		    "drop table test_tab",
		    otl_exception::disabled // disable OTL exceptions
		   ); // drop table

		  otl_cursor::direct_exec
		   (
		    db,
		    "create table test_tab(f1 int, f2 varchar(30))"
		    );  // create table

		  insert(); // insert records into the table
		  update(10); // update records in the table
		  select(8); // select records from the table

	 }

	 catch(otl_exception& p)
	 { // intercept OTL exceptions
		  cerr<
登录后复制

13). 运行结果:

Output

f1=8, f2=Name8
f1=9, f2=Name9
f1=10, f2=Name changed
f1=11, f2=NULL
f1=12, f2=Name12
f1=13, f2=Name13
f1=14, f2=Name14
f1=15, f2=Name15
f1=16, f2=Name16
登录后复制

版权声明:本文为博主原创文章,未经博主允许不得转载。

MyBatis XML 映射器 select、insert update 和 delete、参数

MyBatis XML 映射器 select、insert update 和 delete、参数

MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。 如果跟JDBC 代码进行对比,省掉了将近 95% 的代码。

1 select
CREATE TABLE person (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(100) DEFAULT NULL,
password varchar(100) DEFAULT NULL,
full_name varchar(100) DEFAULT NULL,
first_name varchar(100) DEFAULT NULL,
last_name varchar(100) DEFAULT NULL,
date_of_birth date DEFAULT NULL,
created_on date DEFAULT NULL,
update_on date DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=211 DEFAULT CHARSET=utf8;
insert into person(id,username,password,full_name,first_name,last_name,date_of_birth,created_on,update_on) values (201,''emacarron'',''123456'',''爱德华多·马卡龙'',''爱德华多'',''马卡龙'',''2000-01-01'',''2020-01-01'',''2020-01-02''),(202,''mnesarco'',''123456'',''弗兰克·马丁内斯'',''弗兰克'',''马丁内斯'',''2000-01-01'',''2020-01-01'',''2020-01-02''),(203,''agustafson'',''123456'',''安德鲁·古斯塔夫森'',''安德鲁'',''古斯塔夫森'',''2000-01-01'',''2020-01-01'',''2020-01-02'');
<select id="selectPerson" parameterType="int" resultType="hashmap">
SELECT * FROM PERSON WHERE ID = #{id}
</select>
<select
id="selectPerson"
parameterType="int"
parameterMap="deprecated"
resultType="hashmap"
resultMap="personResultMap"
flushCache="false"
useCache="true"
timeout="10"
fetchSize="256"
statementType="PREPARED"
resultSetType="FORWARD_ONLY">
2 insert, update 和 delete
CREATE TABLE author (
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(100) DEFAULT NULL,
password VARCHAR(100) DEFAULT NULL,
email VARCHAR(100) DEFAULT NULL,
bio VARCHAR(100) DEFAULT NULL,
favourite_section VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB AUTO_INCREMENT=311 DEFAULT CHARSET=utf8;
INSERT INTO author(id,username,password,email,bio,favourite_section) VALUES (301,''克林顿'',''123456'','' clinton.begin@gmail.com'',''MyBatis团队成员'',''打球''),(302,''布兰登'',''123456'','' brandon.goodin@gmail.com'',''MyBatis团队成员'',''听歌''),(303,''亚当'',''123456'',''adam.gent@evocatus.com'',''MyBatis团队贡献者'',''游泳'');
<insert
id="insertAuthor"
parameterType="org.mybatis.example.Author"
flushCache="true"
statementType="PREPARED"
keyProperty=""
keyColumn=""
useGeneratedKeys=""
timeout="20">
<update
id="updateAuthor"
parameterType="org.mybatis.example.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">
<delete
id="deleteAuthor"
parameterType="org.mybatis.example.Author"
flushCache="true"
statementType="PREPARED"
timeout="20">
<insert id="insertAuthor">
insert into Author (id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>
<update id="updateAuthor">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<delete id="deleteAuthor">
delete from Author where id = #{id}
</delete>
<insert id="insertAuthor" useGeneratedKeys="true"
keyProperty="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
SQL
















































































这个元素可以用来定义可重用的 SQL 代码片段,以便在其它语句中使用。

<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>
<select id="selectUsers" resultType="map">
select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from author t1
cross join author t2
</select>
<select id="selectUsers" resultType="map">
select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from author t1
cross join author t2
</select>
3 参数
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(100) DEFAULT NULL,
password varchar(100) DEFAULT NULL,
email varchar(100) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=411 DEFAULT CHARSET=utf8;
insert into users(id,username,password,email) values (401,''admin'',''123456'',''admin@@gmail.com''),(402,''user'',''123456'',''user@gmail.com''),(403,''guest'',''123456'',''guest@gmail.com'');
参数是 MyBatis 非常强大的元素。比如:























<select id="selectUsers" resultType="User">
select id, username, password
from users
where id = #{id}
</select>
如果传入一个复杂的对象,就会有点不一样了。比如:




<insert id="insertUser" parameterType="User">
insert into users (id, username, password)
values (#{id}, #{username}, #{password})
</insert>
字符串替换



有时想在 SQL 语句中直接插入一个不转义的字符串。 比如 : ORDER BY ${columnName}

举个例子,如果你想 select 一个表任意一列的数据时,不需要这样写:

@Select("select from users where id = #{id}")
User findById(@Param("id") long id);
@Select("select

from users where username= #{username}")
User findByUsername(@Param("username") String username);
@Select("select * from users where email = #{email}")
User findByEmail(@Param("email") String email);
而是可以只写这样一个方法:



@Select("select * from users where ${column} = #{value}")
User findByColumn(@Param("column") String column, @Param("value") String value);
其中 ${column} 会被直接替换,而 #{value} 会使用 ? 预处理。

User userOfId = userMapper.findByColumn("id", 401L);
User userOfUsername = userMapper.findByColumn("username", "guest");
User userOfEmail = userMapper.findByColumn("email", "guest@gmail.com");

今天的关于mysql之UPDATE,SELECT,INSERT语法的分享已经结束,谢谢您的关注,如果想了解更多关于6-Python操作MySQL-增(insert)-删(delete)-改(update)-查(select)、c# – TSQL:带INSERT INTO SELECT FROM的UPDATE、C++类库:OTL连接MySQLODBC数据库(insert,update,select)_MySQL、MyBatis XML 映射器 select、insert update 和 delete、参数的相关知识,请在本站进行查询。

本文标签:

上一篇mysql之CREATE DATABASE Syntax(创建数据库)(mysql创建新数据库怎么创建)

下一篇mysql之select语法