i'm trying to connect my unity in sqlite database but i have an error. what does the error means ?
IndexOutOfRangeException: Array index is out of range.
Mono.Data.Sqlite.SqliteDataReader.GetSQLiteType (Int32 i)
Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ)
Mono.Data.Sqlite.SqliteDataReader.GetString (Int32 i)
callOneUser.GetOneUsername () (at Assets/callOneUser.cs:41)
callOneUser.Start () (at Assets/callOneUser.cs:22)
i'm trying to use this code. this is my void Start()
void Start()
{
Connection = "URI=file:" + Application.dataPath + "/English_Booster_Game_DB.s3db"; //Path to database.
GetOneUsername();
}
this is the GetOneUsername() process.
public void GetOneUsername()
{
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string selectoneusername = "select UserData_name from user_data where UserData_status = 1";
dbCmd.CommandText = selectoneusername;
using (IDataReader reader = dbCmd.ExecuteReader())
{
while (reader.Read())
{
name.text = reader.GetString(1);
}
dbConnection.Close();
reader.Close();
}
}
}
}
In your query string, you get one column UserData_name.
string selectoneusername = "select UserData_name from user_data where UserData_status = 1";
It only returns you a column and index in C# start from "Zero". So you should change this line of your script:
name.text = reader.GetString(1);
to:
name.text = reader.GetString(0);
I hope it helps you
Related
I am working on a class Library with .NET Framework 4.0. I have managed to pull a row using ADO.NET, but I'm unable to read individual values. I want the end result in class object. I have tried reading individual value dbReader.GetValue(dbReader.GetOrdinal("BranchCode")) but getting empty result.
Branch class:
public class Branch
{
public Branch() { }
public int BranchId { get; set; }
public string BranchCode { get; set; }
public string BranchName { get; set; }
}
DataReader class:
public void Initialize()
{
try
{
string connectionString = "xyz";
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from dbo.Branch", dbConnection);
dbConnection.Open();
SqlDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var x1 = dbReader.GetValue(dbReader.GetOrdinal("BranchId"));
var x2 = dbReader.GetValue(dbReader.GetOrdinal("BranchCode"));
var x3 = dbReader.GetValue(dbReader.GetOrdinal("BranchName"));
}
var dd = "Dd";
}
catch(Exception ex)
{
throw ex;
}
}
You have a number of issues with your code.
You need to actually create the Branch objects and do something with them. For example, return List.
To read the values, the easiest way is to do (typeNameHere) dbReader["ColumnName"]
You should SELECT exactly the right columns not SELECT *
Don't catch then re-throw exceptions with throw ex; as it wipes the stakc trace.
public List<Branch> Initialize()
{
string connectionString = "xyz";
const string query = #"
Select
b.BranchId,
b.BranchCode,
b.BranchName
from dbo.Branch b;
";
using (SqlConnection dbConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
using (SqlDataReader dbReader = cmd.ExecuteReader())
{
var list = new List<Branch>();
while (dbReader.Read())
{
var b = new Branch();
b.BranchId = (int)dbReader["BranchId"];
b.BranchCode = (string)dbReader["BranchCode"];
b.BranchName = (string)dbReader["BranchName"];
list.Add(b);
}
return list;
}
}
}
I have a DTO class using Moshi that's supposed to send and recieve byte arrays[], but it only works when sending them, because when I recieve then I have this exception.
com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was STRING at path $[0].image
But im pretty sure that the type that the API returns is a byte array.
Here's the DTO class and API controller
#JsonClass(generateAdapter = true)
data class LocationImageDTO (
#Json(name="idLocationImage") val idLocationImage: Int,
#Json(name = "idLocation") val idLocation: Int?,
#Json(name="image") val image: ByteArray,
)
//This one is for recieving
public List<clsLocationImage> getList(int idLocation)
{
List<clsLocationImage> list = new List<clsLocationImage>();
clsLocationImage locationImage;
clsMyConnection connection = new clsMyConnection();
SqlCommand command = new SqlCommand
{
CommandText = "SELECT idLocationImage, idLocation, image FROM K0_MAP_LOCATION_IMAGES WHERE idLocation = #idLocation",
Connection = connection.getConnection()
};
command.Parameters.Add("#idLocation", System.Data.SqlDbType.Int).Value = idLocation;
SqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
locationImage = new clsLocationImage();
locationImage.idLocationImage = (int)reader["idLocationImage"];
locationImage.idLocation = (int)reader["idLocation"];
locationImage.image = (byte[])reader["image"];
list.Add(locationImage);
}
}
}
catch (SqlException excepcion)
{
throw excepcion;
}
return list;
}
public List<clsLocationImage> getListDAL(int id)
{
return getList(id);
}
}
}
///This one is for sending
public int createLocationImage(clsLocationImage locationImage)
{
int filasAfectadas = 0;
clsMyConnection conexion = new clsMyConnection();
SqlCommand miComando = new SqlCommand
{
CommandText = "INSERT INTO K0_MAP_LOCATION_IMAGES(idLocation, image) VALUES (#idLocation, #image)",
Connection = conexion.getConnection()
};
miComando.Parameters.Add("#idLocation", System.Data.SqlDbType.Int).Value = locationImage.idLocation;
miComando.Parameters.Add("#image", System.Data.SqlDbType.VarBinary).Value = locationImage.image;
try
{
filasAfectadas = miComando.ExecuteNonQuery();
}
catch (SqlException excepcion)
{
throw excepcion;
}
return filasAfectadas;
}
}
}
You need to set an explicit JSON adapter to the Moshi Builder.
class CustomDateAdapter : JsonAdapter<Date>() {
private val dateFormat = SimpleDateFormat(SERVER_FORMAT, Locale.getDefault())
#FromJson
override fun fromJson(reader: JsonReader): Date? {
return try {
val dateAsString = reader.nextString()
synchronized(dateFormat) {
dateFormat.parse(dateAsString)
}
} catch (e: Exception) {
null
}
}
#ToJson
override fun toJson(writer: JsonWriter, value: Date?) {
if (value != null) {
synchronized(dateFormat) {
writer.value(value.toString())
}
}
}
companion object {
const val SERVER_FORMAT = ("yyyy-MM-dd'T'HH:mm") // define your server format here
}
}
And then you add it in the Moshi builder
private val moshiBuilder = Moshi.Builder().add(CustomDateAdapter())
private fun getRetrofit(): Retrofit =
Retrofit.Builder()
.baseUrl(MAPK0_API_BASE_URL)
.addConverterFactory(MoshiConverterFactory.create(moshiBuilder.build()))
//.client(getUnsafeOkHttpClient())
.build()
}
Can you please help me see what is wrong with my code? If I run the stored procedure using the a parameter for Id, I get a result in SQL Server. But when I use the code below using the same value for Id, in my if(rdr.HasRows).. I get a false.
public Student Find(int key)
{
string connectionPath = ConnectionStrings.DbConnection;
Student student = null;
try
{
using(var sqlCon = new SqlConnection(connectionPath))
{
sqlCon.Open();
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
{
cmd.Parameters.AddWithValue("#Id", key);
using(var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
if (rdr.HasRows)
{
while (rdr.Read())
{
student = new Student
{
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString(),
Gender = rdr["Gender"].ToString()
};
}
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return student;
}
If I try to get all records, I don't get any problems:
public IEnumerable<Student> GetAll()
{
var studentList = new List<Student>();
try
{
string connectionPath = ConnectionStrings.DbConnection;
using(var sqlCon = new SqlConnection(connectionPath))
{
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
{
sqlCon.Open();
using(var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
studentList.Add
(
new Student
{
Id = Convert.ToInt32(rdr["Id"]),
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString()
}
);
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return studentList;
}
This is using asp.net core
Your code for Find lacks the definition that this is a stored procedure that you're calling.
If you look at your GetAll, you have:
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
defining this SqlCommand to be a stored procedure - this setting is missing from your Find code:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
I'm pretty sure it'll work if you add that:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon) { CommandType = CommandType.StoredProcedure}))
I'm learning asp.net mvc with ado.net, I've got this method in my repository class
public IEnumerable<int?> GetAllUniqueYears()
{
using (IDbConnection dbConnection = dbConnectionFactory.CreateConnection())
{
using (IDbCommand cmd = dbConnection.CreateCommand())
{
cmd.CommandText = "SELECT DISTINCT YEAR(DateAdded) As Year FROM GeoCounters";
cmd.CommandTimeout = 1000;
using (IDataReader reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
yield return null;
}
else
{
yield return (int)reader["Year"];
}
}
}
}
}
When I load my view it's only got a single result, but when I run the query in SQL Server Management Studio there are 4 results
The controller action
public ActionResult Index()
{
HomeIndexViewModel model = new HomeIndexViewModel()
{
GeoCounterDefinitions = geodefrepo.GetAll()
.Select((x,y) => new SelectListItem
{
Text = x.Id + " " + x.FriendlyDesc,
Value = (y + 1).ToString()
}),
Years = geocounterrepo.GetAllUniqueYears()
.Select(x => new SelectListItem
{
Text = x.ToString(),
Value = x.ToString()
})
};
return View(model);
}
You need a while loop.
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
yield return (int)reader["Year"];
}
}
Seems, like a very basic thing, but I could not find it.
I have a bunch of log4j/log4net log files. I would like to dump them into a database in order to be able to analyze them with ease.
I thought I would find a tool to do it in no time, apparently I am wrong.
Does anyone know of such a tool?
OK, so I found no utility. Had to write my own. Of course, it is strictly tailored to my immediate needs (time is money), however, it can save you a bit of time to start your own, in case of a need. Here is the complete code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
public class LogEntry
{
private const string PATTERN = #"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{4}) (\S+) \[(\d+)\] (\w+) (\S+) - (.*)$";
private static readonly Regex s_regex = new Regex(PATTERN, RegexOptions.Compiled);
public DateTime TS;
public string Machine;
public int Thread;
public string Level;
public string Logger;
public string Message;
public static LogEntry TryCreate(string line)
{
var match = s_regex.Match(line);
return match.Success ? new LogEntry
{
TS = DateTime.ParseExact(match.Groups[1].Value, "yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture),
Machine = match.Groups[2].Value,
Thread = int.Parse(match.Groups[3].Value),
Level = match.Groups[4].Value,
Logger = match.Groups[5].Value,
Message = match.Groups[6].Value,
} : null;
}
public void AppendToMessage(string line)
{
Message += Environment.NewLine + line;
}
}
static void Main()
{
const string SQL = #"
INSERT INTO log ( ts, machine, thread, level, logger, message, journalId)
VALUES (#ts, #machine, #thread, #level, #logger, #message, #journalId)
";
using (var connection = new SqlConnection("server=localhost;database=misc;uid=SantaClaus;pwd=MerryChristmas"))
{
connection.Open();
using (var command = new SqlCommand(SQL, connection))
{
var tsParam = new SqlParameter("#ts", SqlDbType.DateTime);
var machineParam = new SqlParameter("#machine", SqlDbType.NVarChar, 32);
var threadParam = new SqlParameter("#thread", SqlDbType.Int);
var levelParam = new SqlParameter("#level", SqlDbType.NVarChar, 10);
var loggerParam = new SqlParameter("#logger", SqlDbType.NVarChar, 128);
var messageParam = new SqlParameter("#message", SqlDbType.NVarChar, -1);
var journalIdParam = new SqlParameter("#journalId", SqlDbType.Int);
command.Parameters.Add(tsParam);
command.Parameters.Add(machineParam);
command.Parameters.Add(threadParam);
command.Parameters.Add(levelParam);
command.Parameters.Add(loggerParam);
command.Parameters.Add(messageParam);
command.Parameters.Add(journalIdParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
int i = 0;
foreach (var file in Directory.GetFiles(#"c:\tmp\dfbje01"))
{
journalIdParam.Value = OpenJournal(connection, file);
command.Transaction = connection.BeginTransaction();
foreach (var e in GetLogEntries(file))
{
tsParam.Value = e.TS;
machineParam.Value = e.Machine;
threadParam.Value = e.Thread;
levelParam.Value = e.Level;
loggerParam.Value = e.Logger;
messageParam.Value = e.Message;
command.ExecuteNonQuery();
++i;
if (i == 1000)
{
i = 0;
command.Transaction.Commit();
command.Transaction = connection.BeginTransaction();
}
}
command.Transaction.Commit();
CloseJournal(connection, journalIdParam.Value);
}
}
}
}
private static void CloseJournal(SqlConnection connection, object id)
{
const string SQL = "UPDATE journal SET done = 1 WHERE id = #id";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#id", id));
command.ExecuteNonQuery();
}
}
private static object OpenJournal(SqlConnection connection, string filePath)
{
const string SQL = "INSERT INTO journal (filePath) OUTPUT inserted.id VALUES (#filePath)";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#filePath", filePath));
return command.ExecuteScalar();
}
}
private static IEnumerable<LogEntry> GetLogEntries(string filePath)
{
LogEntry prev = null;
foreach (var line in File.ReadLines(filePath))
{
var logEntry = LogEntry.TryCreate(line);
if (logEntry != null)
{
if (prev != null)
{
yield return prev;
}
prev = logEntry;
}
else if (prev != null)
{
prev.AppendToMessage(line);
}
else
{
// Oops
Console.WriteLine(line);
}
}
if (prev != null)
{
yield return prev;
}
}
}
}
Mind trying out the filtering, search, colorizing features of the latest developer snapshot of Chainsaw? It has a good number of features which may avoid the need to use a DB. If you use a VFSLogFilePatternReceiver, it can parse and tail any regular text file, including those created by log4net.
Latest developer snapshot of Chainsaw is available here:
http://people.apache.org/~sdeboy