我想在python环境中创建一个mysql数据库,然后在其中创建表,但是错误显示“未选择数据库”。我该如何解决?
import mysql.connector
dbname = input('Please enter the name of database : ')
db = mysql.connector.connect(
host = '127.0.0.1',
user = 'root',
password = ''
)
cursor = db.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %dbname)
cursor.execute("CREATE TABLE IF NOT EXISTS %s (email varchar(30) pwd varchar(20))" %dbname)
db.close()
答案 0 :(得分:1)
在您的代码中,创建数据库连接器后无法识别数据库名称,因为未为连接器提供数据库名称。这意味着在数据库中创建表时,必须向连接器提供数据库名称,然后才能在指定的数据库中创建表通过连接器。
首先,您需要按照以下步骤创建数据库。
public class FarsiBadr extends Fragment {
RecyclerViewAdapter myAdapter;
List<Items> lstItems;
public FarsiBadr() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_farsi_badr, container, false);
lstItems = new ArrayList<>();
lstItems.add(new Items("1 Tv", "11111", "77777", "horizental", R.drawable.gemtv));
lstItems.add(new Items("2 Tv", "22222", "88888", "horizental", R.drawable.bbc));
lstItems.add(new Items("3 Tv", "33333", "99999", "horizental", R.drawable.voa));
lstItems.add(new Items("4 Tv", "44444", "44444", "horizental", R.drawable.manoto));
//horizontal recycler view
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_Horizental_badr_farsi);
myAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
myrv.setAdapter(myAdapter);
//vertical mode
RecyclerView verticalmode = view.findViewById(R.id.recyclerview_id_vertical_badr_farsi);
myAdapter = new RecyclerViewAdapter(getContext(), lstItems);
verticalmode.setLayoutManager(new GridLayoutManager(getContext(), 3));
verticalmode.setAdapter(myAdapter);
return view;
}
}
创建数据库后,您需要手动提供数据库名称才能在现有数据库中创建数据库表。这里dbname由用户即输入
import mysql.connector
dbname = input('Please enter the name of database : ')
db = mysql.connector.connect(
host = 'localhost',
user = 'root',
password = '',
)
cursor = db.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS %s" %dbname)
cursor.close()
db.close()}
最后,您可以要求用户输入数据库名称,并可以使用以下代码在数据库中以相同的名称(在您的情况下为dbname)创建表。
import mysql.connector
db = mysql.connector.connect(
host = 'localhost',
user = 'root',
password = '',
database=dbname, #providing name of database to connector
)
cursor = db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS %s (email VARCHAR(30),pwd
VARCHAR(20))" %dbname)
cursor.close()
db.close()}