会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132440个问题

from sqlalchemy.ext.declarative import declarative_base
# 导入常见数据类型
from sqlalchemy import create_engine,Column,Integer,String,Float,DECIMAL,Boolean,\
    Date,DateTime,Time,Text,Enum
from sqlalchemy.dialects.mysql import LONGTEXT

from sqlalchemy.orm import sessionmaker

from sqlalchemy import func,and_,or_,ForeignKey

HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'first_sqlalchemy'
USERNAME = 'root'
PASSWORD = '123456'

DB_URI ="mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)

engine = create_engine(DB_URI)

session = sessionmaker(engine)()
# 1.用`declarative_base`根据`engine`创建一个ORM基类
Base = declarative_base(engine)

# 需求:sqlalchemy中query查询函数可以传递的参数有哪些(3中方式)
'''
1. 模型名。指定查找这个模型中所有的属性(对应查询表为全表查询)。
2. 模型中的属性。可以指定只查找某个模型的其中几个属性。
3. 聚合函数。
    * func.count:统计行的数量。
    * func.avg:求平均值。
    * func.max:求最大值。
    * func.min:求最小值。
    * func.sum:求和。
    `func`上,其实没有任何聚合函数。但是因为他底层做了一些魔术,
    只要mysql中有的聚合函数,都可以通过func调用
'''

# class News(Base):
#     __tablename__='news'
#     id = Column(Integer,primary_key=True,autoincrement=True)
#     title =Column(String(50),nullable=False)
#     price = Column(Integer)
#     content = Column(Text)
#
#     def  __repr__(self):
#         return  "<title:%s,price:%s,content:%s>"%(self.title,self.price,self.content)
# Base.metadata.drop_all()
# Base.metadata.create_all()

# 添加测试数据
# for x in range(1,6):
#     a = News(title="新闻%s"%x,price =random.randint(1,100))
#     session.add(a)
# session.commit()

# 需求:SQLALchemy实现外键及其四种约束讲解

# 主表 / 从表
# user/news
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer,primary_key=True,autoincrement=True)
    uname = Column(String(50),nullable=False)

    def __repr__(self):
        return "<User(uname:%s)>" % self.uname

class News(Base):
    __tablename__ = 'news'
    id = Column(Integer,primary_key=True,autoincrement=True)
    title = Column(String(50),nullable=False)
    content = Column(Text,nullable=False)
    # sqlalchemy实现外键方法:四种约束
    # RESTRICT
    # uid = Column(Integer,ForeignKey("user.id",ondelete='RESTRICT'))
    # NO ACTION
    uid = Column(Integer,ForeignKey("user.id",ondelete='NO ACTION'))
    # NO ACTION
    # uid = Column(Integer, ForeignKey("user.id", ondelete='CASCADE'))
    # NO ACTION
    # uid = Column(Integer, ForeignKey("user.id", ondelete='SET NULL'))

    def __repr__(self):
        return "<News(title:%s,content=%s)>" % (self.title,self.content)

# 创建表
Base.metadata.drop_all()
Base.metadata.create_all()

# 添加测试数据
user = User(uname='momo')
session.add(user)
session.commit()
#
news1= News(title='AAA',content='123',uid=1)
news2= News(title='BBB',content='456',uid=1)
session.add_all([news1,news2])
session.commit()


image.png



image.png

老师,我的代码,好像外键添加不上去,运行sql语句,直接删除了user表中内容。


Python 全系列/第八阶段:轻量级Web开发利器-Flask框架/Flask数据库 8720楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/异常机制 8721楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 8722楼

老师好,不知道为什么我的聊天室客户端和服务端只能收到一半的回复,多线程一般要怎么调试。

package com.casco.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
 public static void main(String[] args) throws IOException {
  System.out.println("-----服务器端已启动-----");
  ServerSocket serverSocket = new ServerSocket(9999);
  Socket socket = serverSocket.accept();
  DataInputStream dis = new DataInputStream(socket.getInputStream());
  DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
  while(true){
   System.out.println("客户端发送的数据为:" + dis.readUTF());
   dos.writeUTF("服务器端收到了" + dis.readUTF());
  }
  //CloseUtil.closeAll(dos,dis,socket);
 }
}

package com.casco.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class TestClient {
 public static void main(String[] args) throws IOException {
  Socket socket = new Socket("localhost",9999);
  SendThread sendThread = new SendThread(socket);
  ReceiveThread receiveThread = new ReceiveThread(socket);
  new Thread(sendThread).start();
  new Thread(receiveThread).start();
 }
}

package com.casco.client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
public class SendThread implements Runnable {
 private BufferedReader br;
 private DataOutputStream dos;
 private boolean flag = true;
 public SendThread(Socket socket) {
  br = new BufferedReader(new InputStreamReader(System.in));
  try {
   dos = new DataOutputStream(socket.getOutputStream());
  } catch (IOException e) {
   flag = false;
   CloseUtil.closeAll(dos);
  }
 }
 public String getMessage() {
  String str = "";
  try {
   str = br.readLine();
  } catch (IOException e) {
   flag = false;
   CloseUtil.closeAll(br);
  }
  return str;
 }
 public void send(String str) {
  try {
   dos.writeUTF(str);
   dos.flush();
  } catch (IOException e) {
   flag = false;
   CloseUtil.closeAll(dos);
  }
 }
 @Override
 public void run() {
  while(true){
   send(getMessage());
  }
 }
}

package com.casco.client;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class ReceiveThread implements Runnable {
 private DataInputStream dis;
 private boolean flag = true;

 public ReceiveThread(Socket socket) {
  try {
   dis = new DataInputStream(socket.getInputStream());
  } catch (IOException e) {
   flag = false;
   CloseUtil.closeAll(dis);
  }
 }
 public String getMessage() {
  String str = "";
  try {
   str = dis.readUTF();
  } catch (IOException e) {
   flag = false;
   CloseUtil.closeAll(dis);
  }
  return str;
 }
 @Override
 public void run() {
  while(true){
   System.out.println(this.getMessage());
  }
 }
}

image.png

image.png


JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 8724楼

package com.bjsxt.io;

import java.io.Serializable;
import java.util.ArrayList;

/** 
 * <p>Title: Class403</p>  
 * <p>Description: 自定义对象2(将对象序列化写入文件中)</p>  
 * @author xiaoding
 * @date Jun 10, 2020  
 * @version 1.0 
 */
public class Class403 implements Serializable {
    //功能属性
    private int classs;        //班级
    private ArrayList<Student> a1;  //学生
//    private int num;
    //构造方法
    Class403() {
        super();
    }
    public Class403(int classs,ArrayList<Student> a1) {
        this.classs = classs;
        this.a1 = a1;
    }
    
    //get、set方法
    public int getClasss() {
        return classs;
    }
    public void setA1(ArrayList<Student> a1) {
        this.a1 = a1;
    }
    public ArrayList<Student> getA1() {
        return a1;
    }
    public void setClasss(int classs) {
        this.classs = classs;
    }
    
    //toString方法
    @Override
    public String toString() {
        return "Class403 [classs=" + classs + ", a1=" + a1 + "]";
    }
}



package com.bjsxt.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/** 
 * <p>Title: TestClass403</p>  
 * <p>Description: 测试类2测试序列化和反序列化</p>  
 * @author xiaoding
 * @date Jun 10, 2020  
 * @version 1.0 
 */
public class TestClass403 {
    //写入对象
    public static void write() {
        //创建ArrayList对象,写入学生信息
        ArrayList<Student> a1 = new ArrayList<Student>();
        a1.add(new Student(0,"张三",20));
        a1.add(new Student(1,"李四",30));
        a1.add(new Student(2,"王五",25));
        a1.add(new Student(3,"小明",18));
        ObjectOutputStream fis = null;
        //创建ObjectOutputStream写入对象
        try {
            fis = new ObjectOutputStream(new FileOutputStream("D:/student.txt"));
            fis.writeObject(new Class403(403,a1));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            //关闭IO流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    //读取对象
    public static void read() {
        //创建ObjectInputStream
        ObjectInputStream fis = null;
        try {
            fis = new ObjectInputStream(new FileInputStream("D:/student.txt"));
            //读取对象
            System.out.println(fis.readObject());
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            //关闭IO流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    //main方法
    public static void main(String[] args) {
        //write();
        read();
    }
}

首先第一次序列化对象,Class403的属性值只有两个,先写入在自读取

批注 2020-06-10 223855.png

第二次,更改Class403的实例属性,

//    private int num; 解除注释

输出方法还是上面图片那样,他会报错,因为版本不兼容,需要指定版本号

但是我改成这样输出就不会报错,为什么?

批注 2020-06-10 224344.png


JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 8725楼

电商后台.zip

老师我的这个token验证一直是密码错误。数据也是跟着视频提交的,数据库也存在的

Python 全系列/第十阶段:Flask百战电商后台项目/Flask百战电商后台项目 8726楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 8728楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637